Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

Re: using next in a nested foreach()

by gryphon (Abbot)
on Aug 16, 2005 at 01:36 UTC ( #484040=note: print w/replies, xml ) Need Help??

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; } } }


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 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, Inc.

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://484040]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (3)
As of 2023-03-21 08:56 GMT
Find Nodes?
    Voting Booth?
    Which type of climate do you prefer to live in?

    Results (59 votes). Check out past polls.