Beefy Boxes and Bandwidth Generously Provided by pair Networks
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??


in reply to for loops and 'and'

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.

open my $fh, '<', $file or die "could not open file";

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.

@array or print "array empty\n";

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.

@array=undef; @array or print "array empty\n";

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.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (2)
As of 2024-04-25 03:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found