Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: What is true and false in Perl?

by bangers (Pilgrim)
on Apr 16, 2009 at 15:21 UTC ( #758013=note: print w/ replies, xml ) Need Help??


in reply to What is true and false in Perl?

"0 but true" is (a bit) interesting:

use strict; use warnings; print "0 but true" ? "true\n" : "false\n"; print "0 but true" + 0 ? "true\n" : "false\n"; print "0 but true" + 1 ? "true\n" : "false\n";
No warnings using numeric addition on a string, despite the 'use warnings'. Also the second case is unexpected. Shouldn't 'True' + 1 be true?


Comment on Re: What is true and false in Perl?
Download Code
Replies are listed 'Best First'.
Re^2: What is true and false in Perl?
by ig (Vicar) on Apr 17, 2009 at 02:32 UTC
Re^2: What is true and false in Perl?
by morgon (Deacon) on Apr 17, 2009 at 01:06 UTC
    Why is the second case unexpected?

    "0 but true" is not "True".

    It means "treat me in numeric context as 0, but in boolean context as true".

    So when you do "0 but true" + 0 you are in numeric context, so you effectively do 0+0 which is 0 and this in turn (for the ? operator) is false.

    I find that quite logical (which probably shows that using Perl for too long causes brain-damage).

    And by the way: You are not doing numeric addition on a string, you are evaluating "0 but true" in numeric context (to 0) - therefore no warning.

      And by the way: You are not doing numeric addition on a string, you are evaluating "0 but true" in numeric context (to 0) - therefore no warning.

      That makes no sense. The correct answer is that "0 but true" is special-cased.

      $ perl -wle'print 0+"0 abc"' Argument "0 abc" isn't numeric in addition (+) at -e line 1. 0 $ perl -wle'print 0+"0 but true"' 0
        Only in the context of perl -e, as when run from a script, generates the same error (Argument "0 but true" isn't a numeric in addition (+) at line #. Also, both still print 0. And in both cases the attempt to add the string to 0 is ignored.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://758013]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (6)
As of 2015-08-01 20:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found
    past polls