Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: how do foreach and while affect an array?

by davido (Cardinal)
on Sep 12, 2004 at 16:59 UTC ( [id://390446]=note: print w/replies, xml ) Need Help??


in reply to how do foreach and while affect an array?

Neither foreach nor while implicitly empty arrays. I recommend reading through both perlintro, and then perlsyn to understand Perl's looping constructs better. Particularly, perlsyn give a detailed discussion of Perl's looping mechanisms.

If the behavior you're after is to empty an array, you can use shift or pop to remove one element at a time in a loop, like this:

while ( @array ) { my $element = shift @array; # or "my $element = pop @array;". # Now, do something with $element }

Loops just loop, that's all they do. In the case of for or foreach, they iterate over a list (or an array). In the case of while, they loop until a test condition is false. In the case of until, they loop until a test condition is true.

In the case of foreach ( @array ) loops, while the loop itself is non-destructive, the special variable $_ is aliased to each element in the array, one by one as foreach iterates over the array (or list). This means that if you modify $_, the effect will ripple back into the array over which you're iterating, so be careful. This also applies to the iterator variable in foreach loops, even if a named iterator is declared, eg. "foreach my $element ( @array ) {....". Also note that it is almost always a bad idea to add or remove elements from an array while looping over it via foreach as it leads to ambiguity such as "are you looping over the newly resized array, or the original?"


Dave

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (5)
As of 2024-04-19 21:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found