简体   繁体   English

为什么 Perl 在 boolean 上下文中评估具有单个 undef 值的数组为真?

[英]Why does Perl evaluate an array with a single undef value as true in boolean context?

Why is this snippet of code doesn't prints "2"?为什么这段代码不打印“2”?

#!/usr/bin/perl

sub get_undef() {
        return undef;
}

my $test1 = get_undef;
my @test2 = get_undef;

print "1\n" unless ($test1);
print "2\n" unless (@test2);

Your @test2 array contains one value ( undef ).您的@test2数组包含一个值( undef )。

The conditional puts the array in scalar context, which results in the size of the array (1).条件将数组置于标量上下文中,这导致数组的大小 (1)。

If you want $test to be undefined and @test2 to be empty, you can just return;如果您希望$test未定义且@test2为空,则可以return; from your sub.从你的潜艇。

The array @test2 has one element: undef .数组@test2有一个元素: undef In scalar context, this array is not empty, so evaluated to true.在标量上下文中,此数组不为空,因此计算为真。

Perl lets you have a list with the single value undef. Perl 让您拥有一个包含单个值 undef 的列表。 It can be just as meaningful as any other value, although you have to decide what you want it to mean in your context.它可以与任何其他值一样有意义,尽管您必须决定您希望它在您的上下文中意味着什么。

In scalar context, the value of an array is the number of elements in that array.在标量上下文中,数组的值是该数组中元素的数量。 Note this is different than the idea of "list in scalar context" which isn't a thing.请注意,这与“标量上下文中的列表”的想法不同,后者不是一回事。 An array is a container that holds a list and has its own behavior.数组是一个容器,它包含一个列表并有自己的行为。 You can shift an array, but not a list, for instance.例如,您可以shift数组,但不能移动列表。

If you wanted to check that an array had at least one defined value, you can use grep :如果你想检查一个数组是否有至少一个定义的值,你可以使用grep

if( grep { defined } @array ) { ... }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM