Reputation: 2675
Do these 2 statements mean the same thing?
if ($host eq '') {
print "Host exists\n";
}
And
if (defined $host) {
print "Host exists\n";
}
Upvotes: 1
Views: 98
Reputation: 753900
Even if you changed the first to:
if ($host ne '') ...
the two statements are not equivalent, as you'd see if you ran with warnings enabled and left $host
undefined.
$ perl -we 'my $host; print $host ne "" ? "Hi\n" : "Lo\n";'
Use of uninitialized value $host in string ne at -e line 1.
Lo
$ perl -we 'my $host; print defined $host ? "Hi\n" : "Lo\n";'
Lo
$ perl -we 'my $host = ""; print defined $host ? "Hi\n" : "Lo\n";'
Hi
$ perl -we 'my $host = ""; print $host ne "" ? "Hi\n" : "Lo\n";'
Lo
$
Note that one of the answers is "Hi". The empty string is a fine value; it is not the same as undef
.
Upvotes: 3
Reputation: 993143
No, they are different. One is comparing $host
to the empty string, and the other is checking to see whether $host
is defined at all (and may have any value).
Upvotes: 7