Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re^2: process array with while loop

by reason2006 (Novice)
on Nov 09, 2006 at 17:23 UTC ( [id://583166] : note . print w/replies, xml ) Need Help??


in reply to Re: process array with while loop
in thread process array with while loop

Thanks guys. I'll switch to using foreach.

Replies are listed 'Best First'.
Re^3: process array with while loop
by suaveant (Parson) on Nov 09, 2006 at 18:30 UTC
    There is one time when you will want to use a while loop for an array (that I can think of) and that is if you are adding items to the array while iterating through it. for(each) will not reflect changes to the array once the loop has started. A good example of something like this is traversing a directory structure....
    #This code not tested my @dirs = '.'; while(my $dir = shift @dirs) { opendir(DIR,$dir); while(my $entry = readdir(DIR)) { if(-d $entry) { push @dirs, "$dir/$entry"; } else { #do something for files/links etc } } closedir(DIR); }
    Just thought I would point that out. for basically makes an in-memory copy of the list when it first starts.

                    - Ant
                    - Some of my best work - (1 2 3)

      In order to to allow "", 0, undef, etc in the array, the general form would be

      while (@array) { my $item = shift @array; # or pop ... push(@array, ...); # or unshift ... }

      (It's not a problem in your case since every item in @dirs starts with ..)

      This model is useful to perform recursive processes without using recursion.