Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: how do foreach and while affect an array?

by davido (Archbishop)
on Sep 12, 2004 at 16:59 UTC ( #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


Comment on Re: how do foreach and while affect an array?
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (11)
As of 2014-07-10 22:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    When choosing user names for websites, I prefer to use:








    Results (217 votes), past polls