arshad has asked for the wisdom of the Perl Monks concerning the following question:

How come an undefined value matches with '0' ? Following code is the one driving me mad. It displays "its 0". I believe by theory undef cant be matched with '0'. Can someone tell me what is the actual reason behind this?
my $a; if($a = = 0 ){ print "its 0"; }

Replies are listed 'Best First'.
Re: Is undef equal to zero
by ikegami (Patriarch) on May 02, 2008 at 08:02 UTC

    If the type of a value isn't the type called for, Perl automatically converts the value to the appropriate type. undef gets converted to zero when a number is expected, such as for the operand of the numerical equality operator (==).

    use strict; use warnings; my $undef; my $non_numeric_str = 'abc'; print "it's 0\n" if $undef == 0; print "it's 0\n" if $non_numeric_str == 0;
    Use of uninitialized value in numeric eq (==) at script.pl line 7. it's 0 Argument "abc" isn't numeric in numeric eq (==) at script.pl line 8. it's 0
Re: Is undef equal to zero
by Anonymous Monk on May 02, 2008 at 04:12 UTC
    == is numeric comparison.
    Non-numeric values are 0 in numeric context (there are exceptions to this).
    undef isn't a number, therefore in numeric context, its 0.
Re: Is undef equal to zero
by quester (Vicar) on May 02, 2008 at 06:37 UTC
    ... and you aren't getting any warnings about this because you didn't use  perl -w.   An even better way of getting useful warnings is to use following two lines, which you will want to commit to memory and use at the beginning of any script that shows the least sign of a bug:
    use warnings; use strict;
    If you want very verbose mini-tutorials instead of a short messages, add
    use diagnostics;
Re: Is undef equal to zero
by Narveson (Chaplain) on May 02, 2008 at 05:58 UTC
    my $a; if ( $a eq '' ) { print "it's the empty string"; } # it's the empty string if ( $a ) { print "it's true" } else { print "it's false" } # it's false