http://www.perlmonks.org?node_id=484040


in reply to using next in a nested foreach()

Greetings sandrider,

In addition to using labels as two other monks have suggested already, you could use last to exit the inner loop, thus nexting to the outer loop.

foreach my $one (@one) { $one =~ m/\(.\)(.+)\(.\)/; foreach my $two (@two) { if (($1) and ($two eq $1)) { push @result, $one; last; } } }

TMTOWTDI.

Update: I moved the m// outside the inner foreach due to japhy's comment. No idea why I didn't see that before. Doh.

gryphon
Whitepages.com Development Manager (DSMS)
code('Perl') || die;

Replies are listed 'Best First'.
Re^2: using next in a nested foreach()
by Codon (Friar) on Aug 16, 2005 at 17:56 UTC

    This solution, of course, doesn't help with existing deeply nested loops. That's where the labels come in really handy. There is the caveat that the misuse of labels can cause very odd behavior (like the sudden termination of you script) if you are not careful (typos).

    Also, to further optimize (typing optimization; not necessarily execution optimization) based on japhy's comment, you could try this instead:

    push @results, grep { grep { $1 eq $_ } @two if ( $_ =~ /\(.\)(.+)\(.\)/ ) } @one;
    You get to use a nested grep, but you check all values of @two and don't stop when you find a match.

    Update: Since grep will localize $_ and I don't need the outer $_ in the inner grep, I optimized away reassigning the outer $_;

    Ivan Heffner
    Sr. Software Engineer, DAS Lead
    WhitePages.com, Inc.