Yuri Konotopov
Yuri Konotopov

Reputation: 173

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"?

#!/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);

Upvotes: 1

Views: 182

Answers (3)

brian d foy
brian d foy

Reputation: 132812

Perl lets you have a list with the single value 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.

If you wanted to check that an array had at least one defined value, you can use grep:

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

Upvotes: 2

Jim Davis
Jim Davis

Reputation: 5290

Your @test2 array contains one value (undef).

The conditional puts the array in scalar context, which results in the size of the array (1).

If you want $test to be undefined and @test2 to be empty, you can just return; from your sub.

Upvotes: 10

Timur Shtatland
Timur Shtatland

Reputation: 12347

The array @test2 has one element: undef. In scalar context, this array is not empty, so evaluated to true.

Upvotes: 6

Related Questions