我有以下脚本:
#!/usr/bin/perl
use warnings;
use strict;
my $count = 0;
my ( @first , @second , @third );
while ($count <= 7){
push ( @first , $count);
push ( @second , $count) if defined $count;
push ( @third , $count) if $count;
$count++;
}
print "first: @first\n";
print "second: @second\n";
print "third: @third\n";
Run Code Online (Sandbox Code Playgroud)
这会产生以下输出:
first: 0 1 2 3 4 5 6 7
second: 0 1 2 3 4 5 6 7
third: 1 2 3 4 5 6 7
Run Code Online (Sandbox Code Playgroud)
put if defined $count和之间有什么区别if $count,除了后一种方法不会给数组添加零?我搜索了perldocs但找不到答案.
cjm*_*cjm 26
perlsyn中的真理和虚假解释了在布尔上下文中哪些值被认为是假的:
数字0,字符串
'0'和''空列表(),undef在布尔上下文中都是false.所有其他值都是真的.
undef是从未初始化的变量(或已使用该undef函数重置的变量)的值.如果表达式的值不是,则该defined函数返回true undef.
if $count如果$count是数字0,字符串'0',空字符串,undef或者在布尔上下文中使用时已重载以返回其中一项内容的对象,则为false .否则,这是真的.(空列表不能存储在标量变量中.)
if defined $count只有在$count是的时候才是假的undef.
如果你看到perldoc 中定义的文档,那么你会发现它
返回一个布尔值,告知EXPR是否具有未定义值undef以外的值.如果EXPR不存在,则检查$ _.
一个简单的布尔测试不会区分undef,零,空字符串和"0",它们都是同样错误的.
这意味着,
push ( @second , 'undef') if defined $count;
Run Code Online (Sandbox Code Playgroud)
何时$count = 0,然后定义因为0不同于undef和定义返回true,但在这种情况下push ( @third , 'undef') if $count; if condition失败,这就是为什么它没有将0推入数组.