note
muba
<p>Because perl does a lot of automatic data type coercion for you if it's needed.</p>
<p>If undef didn't stringify to "", then what output should this produce?</p>
<c>
print "a" . undef . "b";
</c>
<p>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.</p>
<p>If you need to test for definedness of a value, then you have your [doc://defined|defined function], or your [http://perldoc.perl.org/perlop.html#Logical-Defined-Or|defined-or // operator].</p>
<p>In your last code snipped,
<c>
perl -e 'my $tmp; if( $tmp and ( $tmp eq "" ) ) { print "In\n" } else { print "Out\n" }'
Out
</c>
what output did you expect? Why?</p>
<p>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 <c>$tmp and ( $tmp eq "" )</c>, the <c>and</c> 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 <c>($tmp eq "")</c> is never evaluated in that snippet.</p>
<br/>
<p><b>Addendum:</b> the raison d'&ecirc;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.</p>
1016083
1016083