Syntactic Confectionery Delight | |
PerlMonks |
Re: for loops and 'and'by dga (Hermit) |
on Dec 01, 2003 at 18:29 UTC ( [id://311350]=note: print w/replies, xml ) | Need Help?? |
One thing I didn't see noted but which may aid understanding. Frequently, in normal use of the boolean operators, they are used for something which has a desired side effect. Then the booleans do something really handy. Here is an example of error notification.
Here the open is evaluated in scalar context for a true/false value but in order to know if its true or false, perl has to actually try to open the file to see, so the file opening is a side effect of the boolean test. From the programmer point of view the file test is what's going on and the 'or' is for error checking, but from the program flow it is trying to find out if the left side of the or is true or false.
This would put the array in scalar context and test for true/false, so if the array has elements then this is true even in the following case.
The 'or' never does the print because the assignment made $array[0]=undef;. Thus the array returns true in scalar context and the print isn't done. If you capture the value of this or then you get back the number of elements in the array. Likewise if you capture the value of the open you get back a true value or undef depending on whether the file was opened or not. Using 'or' in these places, leads one to feel that actual work can be performed by the boolean operators, but in reality, if work is done, as in the open case, it is the desired side effect of the call and not the boolean comparison that the programmer is interested in occurring. In fact, as a programmer, one might be happier that the right side of the 'or' with the open was never evaluated at all since that means that the program is not encountering error conditions.
In Section
Seekers of Perl Wisdom
|
|