开发者

Are these 2 statements the same?

开发者 https://www.devze.com 2023-02-05 04:25 出处:网络
Do these 2 statements mean the same thing? if ($ho开发者_如何学Gost eq \'\') { print \"Host exists\\n\";

Do these 2 statements mean the same thing?

if ($ho开发者_如何学Gost eq '') {
    print "Host exists\n";
}

And

if (defined $host) {
    print "Host exists\n";
}


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).


No.

If $host is "localhost", they'll be different.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消