Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re^3: process array with while loop

by suaveant (Parson)
on Nov 09, 2006 at 18:30 UTC ( [id://583182]=note: print w/replies, xml ) Need Help??


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

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)

Replies are listed 'Best First'.
Re^4: process array with while loop
by ikegami (Patriarch) on Nov 09, 2006 at 18:46 UTC

    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.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (5)
As of 2024-04-17 13:22 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found