http://qs1969.pair.com?node_id=390446


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