Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

Re: How come undef eq '' ??

by muba (Priest)
on Jan 30, 2013 at 15:52 UTC ( #1016090=note: print w/replies, xml ) Need Help??

in reply to How come undef eq '' ??

Because perl does a lot of automatic data type coercion for you if it's needed.

If undef didn't stringify to "", then what output should this produce?

print "a" . undef . "b";

With undef stringifying to "", this neatly prints "ab". If undef would stringify to, say, "undef", like how Javascript's null stringifies to "null", the above code would output "aundefb", which hardly seems desireable.

If you need to test for definedness of a value, then you have your defined function, or your defined-or // operator.

In your last code snipped,

perl -e 'my $tmp; if( $tmp and ( $tmp eq "" ) ) { print "In\n" } else +{ print "Out\n" }' Out
what output did you expect? Why?

The reason you're getting "Out" here is not because of how undef stringifies, it's because of undef being considered false. So in the expression $tmp and ( $tmp eq "" ), the and operator looks at its left-hand side, concludes that it's false, and so returns false, causing your if-else to jump to the else part right away. Whether or not ($tmp eq "") is never evaluated in that snippet.

Addendum: the raison d'être of undef is that it can convey the meaning of "there is no valid value for what you asked for," for example if you have a function that returns the next paragraph from some document, then "" would mean that the next paragraph is empty, and undef would mean that there is no next paragraph.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1016090]
[stevieb]: heh, yeah, sorry. This is integration testing for certain. In fact, it's even Continuous Integration ;)
[stevieb]: Obviously, Travis CI just won't cut it for these distributions...
[stevieb]: I went on my merry way writing a cross-platform, network-aware system that works across Perlbrew and Berrybrew systems and runs unit tests for Perl dists on all installed versions, with the ability to manage *brew commands themselves
[stevieb]: That worked out exceptionally well, as when I started that project, I hadn't delved into hardware development yet.
[stevieb]: found a issue in MetaCPAN::Client though today for my revdep tests. At least I think it's an issue

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (4)
As of 2017-06-25 23:29 GMT
Find Nodes?
    Voting Booth?
    How many monitors do you use while coding?

    Results (572 votes). Check out past polls.