gpt4 book ai didi

perl - 分配给变量的未定义值。

转载 作者:行者123 更新时间:2023-12-02 07:22:35 24 4
gpt4 key购买 nike

5 > 6 的返回值是 undef。但是,当我将 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

最佳答案

How do I pass the value of a statement using a comparison operator that resolves to undef on failure?

一般来说,Perl 不 promise 从其运算符返回任何特定的真值或假值,并且 <也不异常(exception)。如果你想要特定的值,你将需要像

$boolean ? $value_for_true : $value_for_false

所以

my $wiz = 5 > 6 ? 1 : undef;

如果你只关心你得到的 false 的值,你也可以使用下面的:

my $wiz = 5 > 6 || undef;

事实证明这两个选项是等价的,但这并不能保证。


The return value of 5 > 6 is undef. However when I assign the value of 5 > 6 to a variable

那不是真的。该变量被分配了一个定义的值,因为 5 > 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 ""

$ 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

关于perl - 分配给变量的未定义值。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41772847/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com