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

Re: Next from inner loop only works "most of the time"

by BillKSmith (Monsignor)
on May 18, 2021 at 13:22 UTC ( #11132710=note: print w/replies, xml ) Need Help??

in reply to Next from inner loop only works "most of the time"

All three of of your loops use the same global variable ($_). Declare a lexical variable for at least two of them.
#UNTESTED RESULT: foreach my $wrd(@result) { my %seen; $seen{$_}++ for (split //,lc $_); foreach my $ltr (keys %seen) { next RESULT if ($seen{$ltr} > $master_letter_freq{$ltr +}); } print "$_\n"; }

UPDATE: Thanks to jo37 (below),I now believe that the original code 'should' work.


Replies are listed 'Best First'.
Re^2: Next from inner loop only works "most of the time"
by jo37 (Hermit) on May 18, 2021 at 16:01 UTC

    I don't think the multiple usage of $_ is problematic here. According to perlsyn the global $_ gets localized in a foreach loop. Indeed:

    #!/usr/bin/perl use v5.16; use warnings; foreach (1, 2) { say for qw(a b); say; foreach (10, 20) { say; } say; } __DATA__ a b 1 10 20 1 a b 2 10 20 2



        I completely agree except I'd go slight further and suggest that anything that is bad for readability is, perforce, bad for maintainability - if you can't read it you can't maintain it (although you may be able to completely replace it).

        Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond
      Nonetheless, "for(each) my $var ..." is what's recommended, and with very good reason. For one thing, inner loops (or the code which they contain) usually needs to be able to refer separately to the loop-indexes of one or more of the outer loops. This achieves that without polluting the namespace.

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (4)
As of 2021-11-27 21:27 GMT
Find Nodes?
    Voting Booth?

    No recent polls found