Item 5: Remember that 0 and are false.


Item 5: Remember that and "" are false.

Because numeric and string data in Perl have the same scalar type, and because Boolean operations can be applied to any scalar value, Perl's test for logical truth has to work for both numbers and strings.

The basic test is this: and the empty string are false . Everything else is true.

More precisely, when a quantity is used in a " Boolean context" (a term sometimes used to refer to conditionals in control expressions, the ?: operator, , && , etc.), it is first converted to a string (see Item 6). The string result is then tested . If the result is the empty string, or a string consisting exactly of the single character "0" , the result is " false." Otherwise, the result is " true." Note that this rule means that undef will evaluate as false, because it always looks like the number or the empty string to everything except the defined operator. This generally works very well. If problems do arise, they are usually the result of testing a quantity to see if it is false when really it should be tested to see if it is undef :

Don't test for falsehood when you should be testing for undef .

 while ($file = <*>) {    do_something($file);  } 

WRONGwhat about a file named "0" ?

The code in this example works well almost all of the time. Each time through the loop, the fileglob <*> produces another filename from the current directory, which goes into $file . Once all the filenames in the directory have been enumerated, <*> returns undef , which appears to be the empty string and therefore false, causing the while loop to terminate.

There is one problem, though. If there is a file named in the current directory, it also appears to be false, causing the loop to terminate early. To avoid this, use the defined operator to test specifically for undef :

Use the defined operator to test for undef .

 while (defined($file = <*>)) {    do_something($file);  } 

CORRECTloop now terminates only when <*> returns undef .

You may also need to use a different strategy when testing to see if an element is present inside a hash. undef is a perfectly acceptable value in a hash:

Suppose %hash is undefined to start.

 if ($hash{'foo'}) { ... }  if (defined($hash{'foo'})) { ... } 

FALSE

Also FALSE.

 $hash{'foo'} = undef;  if (defined($hash{'foo'})) { ... }  print keys %hash; 

Assign an undef value.

Still FALSE.

('foo')

The exists operator can determine whether a particular key is present, even if the corresponding value in the hash is undef :

Continued from above:

 if (exists($hash{'foo'})) { ... } 

TRUE



Effective Perl Programming. Writing Better Programs with Perl
Effective Perl Programming: Writing Better Programs with Perl
ISBN: 0201419750
EAN: 2147483647
Year: 1996
Pages: 116

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net