[Israel.pm] undef vs. ""

Levenglick Dov-RM07994 dov at freescale.com
Wed Jan 7 06:56:22 PST 2009

Just because something evaluates to undef doesn't mean that it is in
itself equal to undef. There is a fine line

Best Regards,
Dov Levenglick
SmartDSP OS Development Leader

-----Original Message-----
From: perl-bounces at perl.org.il [mailto:perl-bounces at perl.org.il] On
Behalf Of Gaal Yahas
Sent: Wednesday, January 07, 2009 14:52
To: Perl in Israel
Subject: Re: [Israel.pm] undef vs. ""

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>
> 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>
Perl mailing list
Perl at perl.org.il

More information about the Perl mailing list