This one just came up: How do I break out of an if
statement? I have a long if statement, but there is one situation where I can break out of it early on.
In
I was inspired by DVK's answer to play around, and I came up with this variant that works at least on Perl 5.26.1:
for( ; some_condition ; last ) {
blah, blah, blah
last if $some_other_condition; # No need to continue...
blah, blah, blah
}
Per perlsyn, this is equivalent to:
while (some_condition) {
blah, blah, blah
last if $some_other_condition; # No need to continue...
blah, blah, blah
} continue {
last;
}
In a continue block, last
has the same effect as if it had been executed in the main loop. Therefore, the loop will execute zero or one times, depending on some_condition
.
perl -E 'my ($cond, $other)=(X, Y);
for(;$cond;last) { say "hello"; last if $other; say "goodbye" }'
has the following results, for various X
and Y
values:
X Y Prints
-----------------------
0 0 (nothing)
0 1 (nothing)
1 0 hello, goodbye
1 1 hello