Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery

Re: Nested Foreach Loop skipping every other element??

by kennethk (Abbot)
on Feb 19, 2014 at 17:44 UTC ( #1075498=note: print w/replies, xml ) Need Help??

in reply to Nested Foreach Loop skipping every other element??

After considering hdb and Kenosis's advice, when I need to iterate over an array I am dropping terms from, I usually use an explicit index and iterate backwards over the indices. Note that you already need to use $delele (which I assume should be $delete) to track the index. As long as you are already tracking it, you might as well include that in your control structure. So maybe your code would read (untested):
use strict; use warnings; use File::Copy; my @files = glob("*.hml"); my @DIR = glob ("*/*.hml"); my @array = ('', grep -d, glob '*'); print "Here's DIR @DIR"; my $argsucess = 0; foreach my $el (@ARGV){ print "\n\n\nheres el $el"; foreach my $delele (reverse 0 .. $#DIR){ my $element = $DIR[$delele]; print "\n\n\nHERE'S ELE $element"; print "\n\n\n\n\n\n HERE'S DIR SO FAR @DIR\n\n\n"; my $re1='((?:[a-z][a-z]+))'; # Non-greedy match on filler my $re=$re1; my $path; if ($element =~m/$re/is){ $path = $1; } if ($el eq $path){ splice(@DIR, $delele, 1); $argsucess++; next; } } }
The benefit to reverse traversal is that you don't interfere with the indices for future iterations by splicing this one out.

You might also consider using qr// for your regular expression (see Regexp Quote Like Operators). I'm a little unclear on why you aren't just using a fixed regular expression in if ($element =~m/$re/is){, nor why you are using the my $re=$re1; misdirection. Also, by initializing my $path; to undef instead of empty string (my $path = '';), you will likely get a number of unnecessary warnings from if ($el eq $path){.

#11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

Replies are listed 'Best First'.
Re^2: Nested Foreach Loop skipping every other element??
by AnomalousMonk (Chancellor) on Feb 19, 2014 at 22:36 UTC
    my $re1='((?:[a-z][a-z]+))'; # Non-greedy match on filler

    ba1688: Also be aware that the quoted regex (also in the OP) is not "non-greedy" either by its definition or by virtue of the way it is used (Update: well, not in any regex-related sense, anyway).

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1075498]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (5)
As of 2018-02-20 09:54 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (268 votes). Check out past polls.