Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

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

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;


Comment on Re: using next in a nested foreach()
Download Code
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.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (6)
As of 2014-12-20 02:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (95 votes), past polls