SPUG: "Boolean" return values

Michael R. Wolf MichaelRWolf at att.net
Tue Oct 14 08:08:37 PDT 2008


craig at seaperl.com wrote:
> The reason that I've always heard was that in an IF condition you could 
> do TRUE if the condition returned a positive number and would be FALSE 
> if it was a numeric 0 or a string. Perl does that sort of conversion so 
> that if you have a string of "345" that it could be evaluated as a 
> NUMERIC 345 and counting as TRUE but that something like "345r2" would 
> be evaluated as a string and be considered FALSE.

Your understanding of strings in a boolean context isn't correct. 
Here's a simple chunk of code that disproves your assertion:

if ("345r2") {
     print "The string was true\n";
}
else {
         print "The string was false\n";
}

Negative numbers are also true.  There are only 2 false numbers: 0 and 
0.0.  Some would argue that that is only one number, but this shows that 
the internal representation is different, even if their use is 
practically identical.

perl -MDevel::Peek -le "Dump(0); Dump(0.0);"
SV = IV(0x10023bc8) at 0x10023bc8
   REFCNT = 1
   FLAGS = (PADTMP,IOK,READONLY,pIOK)
   IV = 0
SV = NV(0x10063810) at 0x1004f650
   REFCNT = 1
   FLAGS = (PADTMP,NOK,READONLY,pNOK)
   NV = 0



In practice, most strings are true.  I know of only 3 false strings:
  1. '', the empty string
  2. '0', the string containing only a single zero
  3. "\000", the ASCII NUL character (AKA chr(0)).



More information about the spug-list mailing list