Perl 未定义分配给变量的值。

Perl 未定义分配给变量的值。,perl,undefined,Perl,Undefined,返回值5>6是未定义的。但是,当我将值5>6赋给变量时,该变量已定义。如何使用比较运算符传递语句的值,该运算符在失败时解析为undef #!/usr/bin/perl use strict ; use warnings; print'Five is more than six ? ', 5 > 6, "\n"; print 'Five is less than six ? ' , 5 < 6 , "\n"; my $wiz = 5 > 6 ; if (define

返回值5>6是未定义的。但是,当我将值5>6赋给变量时,该变量已定义。如何使用比较运算符传递语句的值,该运算符在失败时解析为undef

#!/usr/bin/perl
use strict ;
use warnings;
print'Five is more than six ? ',      5 >  6, "\n";
print 'Five is less than six ? ' , 5 < 6 , "\n";
my $wiz = 5 > 6 ;

if (defined($wiz)) {
    print '$wiz is defined' ;
    } else {
    print '$wiz is undefined' ;
}


$ ./lessthan
Five is more than six ?
Five is less than six ? 1
$wiz is defined
#/usr/bin/perl
严格使用;
使用警告;
打印“五大于六”,5>6,“\n”;
打印“五小于六”,5<6,“\n”;
我的$wiz=5>6;
如果(定义为($wiz)){
打印“$wiz已定义”;
}否则{
打印“$wiz未定义”;
}
美元/少于
五等于六?
五比六小?1.
$wiz已定义

5>6
不是未定义的,但它是一个假值。在本例中,一种
dualvar
,当用作字符串时,它的作用类似于空字符串;当用作数字时,它的作用类似于
0

$ perl -wE'say "> ", "".( undef )'
Use of uninitialized value in concatenation (.) or string at -e line 1.
>

$ perl -wE'say "> ", "".( "" )'
>

$ perl -wE'say "> ", "".( 0 )'
> 0

$ perl -wE'say "> ", "".( 5>6 )'
>                                     # Behaves as ""
因为该值为false,所以可以执行以下操作

if ( $wiz ) { ... }
如果您真的想不定义
$wiz
,可以这样做

my $wiz = 5 > 6 || undef;
现在,如果表达式
5>6
为真,
$wiz
将为
1
,否则将为
undef

如何使用比较运算符传递语句的值,该运算符在失败时解析为undef

#!/usr/bin/perl
use strict ;
use warnings;
print'Five is more than six ? ',      5 >  6, "\n";
print 'Five is less than six ? ' , 5 < 6 , "\n";
my $wiz = 5 > 6 ;

if (defined($wiz)) {
    print '$wiz is defined' ;
    } else {
    print '$wiz is undefined' ;
}


$ ./lessthan
Five is more than six ?
Five is less than six ? 1
$wiz is defined
一般来说,Perl不承诺从其运算符返回任何特定的true或false值,
6
计算为定义值,因此为变量分配了定义值。虽然Perl没有指定它从操作符返回的假值,但它通常返回标量
sv_no
,这是一个dualvar,当作为字符串处理时,它看起来是空字符串,当作为数字处理时,它看起来是零

$ perl -wE'say "> ", "".( undef )'
Use of uninitialized value in concatenation (.) or string at -e line 1.
>

$ perl -wE'say "> ", "".( "" )'
>

$ perl -wE'say "> ", "".( 0 )'
> 0

$ perl -wE'say "> ", "".( 5>6 )'
>                                     # Behaves as ""


布尔false和undef是两个不同的东西

比较赋值在布尔上下文中执行,仅返回布尔值,而undef不是布尔值 切克

if(defined false){
    print "false is also defined thing.."
}else{
    print "else .."
}

回到问题上来,似乎比较不能返回undf

它不是空字符串,而是一个dualvar。当用作字符串时,它的行为类似于空字符串,当用作数字时,它的行为类似于零。请参阅,因此,成功和时小于或大于运算符解析为1失败时为“falsey”,这是一个空字符串,不是未定义的。我只是看到5>6的结果为nothing,或未定义。因此,如果我将5>6的结果分配给变量,您会认为5>6的结果(似乎没有定义)会分配给变量。但是,通过将其赋给变量,您可以定义它.Casper,表达式
5>6
不是空的(或
unde
),而是定义的假值。请尝试此选项查看:
print defined(5>6)?”def':“undef”
$ perl -wE'say "> ", 0+( undef )'
Use of uninitialized value in addition (+) at -e line 1.
> 0

$ perl -wE'say "> ", 0+( "" )'
Argument "" isn't numeric in addition (+) at -e line 1.
> 0

$ perl -wE'say "> ", 0+( 0 )'
> 0

$ perl -wE'say "> ", 0+( 5>6 )'
> 0                                   # Behaves as 0
if(defined false){
    print "false is also defined thing.."
}else{
    print "else .."
}