I have the following script:
#!/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";
This produces the following output:
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
What’s the difference between putting if defined $count vs. if $count, other than the latter method won’t add the zero to the array? I’ve searched the perldocs but couldn’t find the answer.
Truth and Falsehood in perlsyn explains what values are considered false in a boolean context:
undefis the value of a variable that has never been initialized (or that has been reset using theundeffunction). Thedefinedfunction returns true if the value of the expression is notundef.if $countis false if$countis the number 0, the string'0', the empty string,undef, or an object that has been overloaded to return one of those things when used in a boolean context. Otherwise, it’s true. (The empty list can’t be stored in a scalar variable.)if defined $countis false only if$countisundef.