Henry Law <
[email protected]> writes:
I often want to check some condition and if it's true execute one simple statement and then bale out. Written out "long hand" it might be
if ( $mistakes > 2 ){
print "There are too many mistakes\n";
exit;
}
I routinely code it more succinctly like this:
print "There are too many mistakes\n" and exit if $mistakes > 2;
But I've also occasionally copied another formulation, with the comma operator rather than 'and':
print "There are too many mistakes\n", exit if $mistakes > 2;
I see from "perlop" that 'and' is of lower precedence than ',' but that's
not important because I only have one of them; and they're both left- associative. The comma evaluates the "print" (which is always true) and
then evaluates the "if"; whereas the 'and' operator computes first the
left hand side (doing the print) and then if it's true (which it is) the "if". Both of these are what I want.
Can someone explain to me why these are different, if indeed they are,
and which if either is preferable?
There's different because "and" is affected by the result of the print.
Don't assume that print is always successful. (For example, on my
system I can make it fail by redirecting output to "/dev/full".) Even
if you can assume it will always succeed, using "and" says explicitly
that you want your program's behavior to depend on whether print
succeeds or fails.
I don't think you want your program to continue running only if the
print was unsuccessful.
In your example, printing error messages to stdout is probably a bad
idea. The "die" function prints to stderr and terminates the program:
die "There are too many mistakes\n" if $mistakes > 2;
But if that really is the behavior you want, I'd use the comma operator
rather than "and". Or I might write something like this:
do { print "There are too many mistakes\n"; exit } if $mistakes > 2;
Or I might write a small function:
sub die_stdout {
print @_;
exit;
}
die_stdout("There are too many mistakes\n") if $mistakes > 2;
Or, frankly, I'd just write the block. I might consider writing the
whole thing on one line if it's a small throwaway piece of code *or* if
it's part of a sequence of similar statements:
if ($mistakes > 2) { print "There are too many mistakes\n"; exit; }
if ($goofs > 3) { print "There are too many goofs\n"; exit; }
# ...
Again, I wouldn't write error messages to stdout, and "die" is designed
for this, but perhaps that aspect wasn't central to what you're asking.
--
Keith Thompson (The_Other_Keith)
[email protected]
Working, but not speaking, for Philips Healthcare
void Void(void) { Void(); } /* The recursive call of the void */
--- SoupGate-Win32 v1.05
* Origin: fsxNet Usenet Gateway (21:1/5)