Not really knowing Perl, I have been enhancing a Perl script with help from a friendly search engine.
I find that I need to break out of a loop while setting a flag if a condition comes true:
foreach my $element (@array) {
if($costlyCondition) {
$flag = 1;
last;
}
}
I know that the nicer way to use ‘last’ is something like this:
foreach my $element (@array) {
last if ($costlyCondition);
}
Of course, this means that while I can enjoy the syntactic sugar, I cannot set my flag inside the loop, which means I need to evaluate $costlyCondition once again outside.
Is there a cleaner way to do this?
you can use a
do {...}block:you can use the
,operator to join the statements:you can do the same with the logical
&&operator:or even the lower priority
and:at the end of the day, there’s no real reason to do any of these. They all do exactly the same as your original code. If your original code works and is legible, leave it like it is.