in reply to Perl Best Practices - Loop Labels
The $work questions generally centred around whether jumping out of nested loops, starting the next iteration of a loop early, and so on, was a good practice.
So say you need to search through a bunch of files to see if Joe Bloggs is mentioned in any of them. You don't care which files he's mentioned in, or how many times. You just want a boolean — is he mentioned at all?
my $mentioned = 0; FILE: for my $file ( @files ) { LINE: for my $line ( @lines ) { /Joe Bloggs/ and ++$mentioned and last FILE; } } return $mentioned;
The question of whether it's good practice to jump out of nested loops becomes "after I've found the answer to my question, should I keep searching through the rest of the files?"
Or another way of thinking about it: "after I found my lost car keys, should I keep looking for them?"
I'm sure there are good times to jump out of loops and bad times to jump out of loops, and there are many subtle nuances. But in the general case, if you know a loop has served its purpose, jump out of it.
(Oh, and another thing. You'll notice I labelled my inner loop too, even though I never used that label. I find labelling loops, especially nested loops can be a form of documentation.)
Update:, please, please don't do this though:
my $mentioned = 0; FILE: for my $file ( @files ) { check_file($file, \$mentioned); } return $mentioned; ...; sub check_file { my ($file, $mentioned) = @_; LINE: for my $line ( @lines ) { /Joe Bloggs/ and ++$$mentioned and last FILE; } }
Yes, Perl does let last to be in a subroutine called from the loop. Don't do that. It's really hard to grok. Only use next, last, and redo lexically within the loop block they affect.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Perl Best Practices - Loop Labels
by kcott (Archbishop) on Apr 16, 2020 at 07:57 UTC | |
|
Re^2: Perl Best Practices - Loop Labels
by talexb (Chancellor) on Apr 16, 2020 at 13:20 UTC |