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?
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.
In your example, printing error messages to stdout is probably a bad
idea. The "die" function prints to stderr and terminates the program:
print "There are too many mistakes\n", exit if $mistakes > 2;
"Henry" == Henry Law <news@lawshouse.org> writes:
"Rainer" == Rainer Weikusat <rweikusat@talktalk.net> writes:
"Rainer" == Rainer Weikusat <rweikusat@talktalk.net> writes:
Rainer> Tangential issue: This exits with a status code of 0 whose usual Rainer> meaning is "it worked". Using an error status code (anything
Rainer> except 0) is probably a better idea here.
Which is why I use "die" far more often than I use "exit".
"die" would be much more useful if it would support formatted output à
la printf and didn't have the annoying habit of mangling its arguments
with all kinds "I'm sure you'll want that!" stuff.
No, in this case, because print is gathering a list, which includes the "result" of the exit invocation, nothing will get printed, because the
exit will have already executed. Common mistake to have things nearby a list-gathering function.
"Henry" == Henry Law <news@lawshouse.org> writes:
I *do* have a fair amount of practice at explaining things... Perl in particular.
Sysop: | Keyop |
---|---|
Location: | Huddersfield, West Yorkshire, UK |
Users: | 296 |
Nodes: | 16 (2 / 14) |
Uptime: | 59:31:12 |
Calls: | 6,653 |
Calls today: | 5 |
Files: | 12,200 |
Messages: | 5,331,283 |