Re: use of next versus last in a nested loop algorithm

Paul Lalli wrote:
markpark wrote:
if there is a match, i want to get
out of the foreach my $pat loop and go to the next $item in the
foreach my $item loop on the outside. i've read about next and last in
various books and still i can't tell what to use because
my case is a little different than the examples in the books because i
am comparing values in
the two loops to decide when to get out. therefore, i don't think
whatever statement i use, next
or last, can go in the if statement ?

foreach my $item (@filelist) {
foreach my $pat (@datelist2array) {
if ( $item =~ /$pat/ ) {
print $out_file2 "$item \n";

if() {} is not a looping construct, and therefore next and last have no
effect on it. If you put a next; inside the if statement, that will
start the next iteration of the inner for loop. If you put a last;
inside the if statement, that will end the inner for loop.

If you're really paranoid about what loop a next/last applies to, label
your blocks explicitly:

ITEM: foreach my $item(@filelist) {
PAT: foreach my $pat (@datelist2array) {
if ($item =~ /$pat/) {
print $out_file2 "$item \n";
next ITEM;
#or, equivalently in this case
# last PAT;

it's not just for the paranoid, Paul. it's a Best Practice. :-D


PS: loop labels on the preceding line :-P
PPS: you will be assimilated.