Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

Re: process array with while loop

by grep (Monsignor)
on Nov 09, 2006 at 17:16 UTC ( [id://583162]=note: print w/replies, xml ) Need Help??

in reply to process array with while loop

This is bad practice.If you read perlop: I/O Operators carefully you'll see < > are special for filehandles. You'll most likely run into weird problems if the list is empty.

Also qw does not need (or want) commas. It should be more like:

use strict; use warnings; my @array = qw( blue red orange brown ); foreach (@array) { print "$_\n"; }

One dead unjugged rabbit fish later

Replies are listed 'Best First'.
Re^2: process array with while loop
by reason2006 (Novice) on Nov 09, 2006 at 17:23 UTC
    Thanks guys. I'll switch to using foreach.
      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.

Log In?

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

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (5)
As of 2024-04-18 14:41 GMT
Find Nodes?
    Voting Booth?

    No recent polls found