AtomicPorkchop
AtomicPorkchop

Reputation: 2675

Are these 2 statements the same?

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

Answers (3)

Jonathan Leffler
Jonathan Leffler

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

Greg Hewgill
Greg Hewgill

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

SLaks
SLaks

Reputation: 887453

No.

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

Upvotes: 4

Related Questions