[Israel.pm] undef vs. ""

Gaal Yahas gaal at forum2.org
Wed Jan 7 04:52:22 PST 2009


As sawyer says, you should use "defined" for these tests.

Perl coerces certain values for you if you try to use them in places
where they don't immediately fit. The == operator numifyies it
arguments, and all of the following print "yes":

perl -wle 'print "yes" if 0 == 0'
perl -wle 'print "yes" if "0" == 0'
perl -wle 'print "yes" if "" == 0'  # warns Argument "" isn't numeric
in numeric eq
perl -wle 'print "yes" if undef == 0'  # warns Use of uninitialized
value in numeric eq

Undef also stringifies to an empty string:

perl -wle 'print "yes" if undef eq ""'  # warns Use of uninitialized
value in string eq

Putting time into your code so that it doesn't emit any warnings is a
good investment.

PS: sawyer, "undef" always returns an undef value, and although this
fact isn't as widely useful as Chanan wished it to be because of the
warning it'd trigger when used for comparisons, it can still be
exploited legitimately in some cases.

On Wed, Jan 7, 2009 at 10:32 AM, Chanan Berler <chananb at centerity.com> wrote:
> Hi All,
>
> I wonder if I should consider "" equal to undef.
> If it is so..then is there an empty string? Or there is not
>
> Please consider this as an example:
> =========================================
>
> print "undef" if ($" == undef);    ----> will print: undef
> print "found \"\"" if ($" == "");  ----> will print: found ""
>
> so I can understand that $" == "" == undef
>
> So why do I get a warning message, when doing this:
> $var = undef . "string";
>
> But never get this warning message when doing:
> $var = "string" . undef
>
> Also I found that when trying to do this, no warning is out
> $var = "" . "string";
> $var = "string" . "";
>
> PS: another thing I found, different warnings when using "use warnings;" -
>
> Is this a bug in perl, or just a fact? Or lets say a "known issue"
> Thanks
> Chanan
>
> _______________________________________________
> Perl mailing list
> Perl at perl.org.il
> http://perl.org.il/mailman/listinfo/perl
>



-- 
Gaal Yahas <gaal at forum2.org>
http://gaal.livejournal.com/



More information about the Perl mailing list