Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

How can I differentiate between 0 and whitespace in Perl?

by boom (Scribe)
on Apr 18, 2009 at 13:35 UTC ( [id://758466]=perlquestion: print w/replies, xml ) Need Help??

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

I have the following piece of code in my program:

$val = chr(someFunction()); if($val == " ") { #do something } elsif($val == 0) { #do something else }

But whenever 0 is passed to $val, the if part executes instead of the elsif which I expect to get executed. How can I fix this?

Replies are listed 'Best First'.
Re: How can I differentiate between 0 and whitespace in Perl?
by syphilis (Archbishop) on Apr 18, 2009 at 14:04 UTC
    When you use "==", both the left and right sides are evaluated in numeric context. Since, in numeric context, " " and 0 are equivalent (and are also numerically equivalent to both undef and "" btw), your 'if' and 'elsif' conditions are effectively identical.

    That is, if $val == " " is true, then so is $val == 0, and vice-versa

    Cheers,
    Rob
Re: How can I differentiate between 0 and whitespace in Perl?
by Anonymous Monk on Apr 18, 2009 at 13:51 UTC
Re: How can I differentiate between 0 and whitespace in Perl?
by codeacrobat (Chaplain) on Apr 19, 2009 at 10:05 UTC
    use feature ":5.10"; $val=" "; given($val) { when (" ") { print "space"} when (0) { print "zero"} default { print "other" } }

    print+qq(\L@{[ref\&@]}@{['@'x7^'!#2/"!4']});

      Side note:  I'd use 5.010; instead of use feature ":5.10";.  The net effect is the same, but the innocent/inexperienced user of an older version of Perl will probably appreciate a clear message indicating what the problem is, i.e.

      $ perl -M5.010 -e1 Perl v5.10.0 required--this is only v5.8.8, stopped at ... vs. $ perl -Mfeature=:5.10 -e1 Can't locate feature.pm in @INC (@INC contains: ...

      with no mention of 5.10 in the latter.

        Then this should be fixed in perlsyn, because use feature ":5.10" is what you find there. *sigh* The 5.10 vs. 5.010 syntax is nasty.

        print+qq(\L@{[ref\&@]}@{['@'x7^'!#2/"!4']});
        Then they'll comment out #use 5.010; and be equally confused ;)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://758466]
Approved by planetscape
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (4)
As of 2024-04-20 00:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found