note
davido
<p>Neither <code>foreach</code> nor <code>while</code> implicitly empty arrays. I recommend reading through both [doc://perlintro], and then [doc://perlsyn] to understand Perl's looping constructs better. Particularly, [doc://perlsyn] give a detailed discussion of Perl's looping mechanisms.
</p>
<p>If the behavior you're after is to empty an array, you can use [doc://shift] or [doc://pop] to remove one element at a time in a loop, like this:
</p>
<code>
while ( @array ) {
my $element = shift @array;
# or "my $element = pop @array;".
# Now, do something with $element
}
</code>
<p>
Loops just loop, that's all they do. In the case of <code>for</code> or <code>foreach</code>, they iterate over a list (or an array). In the case of <code>while</code>, they loop until a test condition is false. In the case of <code>until</code>, they loop until a test condition is true.
</p>
<p>In the case of <code>foreach ( @array )</code> loops, while the loop itself is non-destructive, the special variable <code>$_</code> is aliased to each element in the array, one by one as <code>foreach</code> iterates over the array (or list). This means that if you modify <code>$_</code>, the effect will ripple back into the array over which you're iterating, so be careful. This also applies to the iterator variable in <code>foreach</code> loops, even if a named iterator is declared, eg. "<code>foreach my $element ( @array ) {....</code>".
Also note that it is almost always a <em>bad idea</em> to add or remove elements from an array while looping over it via <code>foreach</code> as it leads to ambiguity such as "are you looping over the newly resized array, or the original?"
</p>
<div class="pmsig"><div class="pmsig-281137">
<br /><p>Dave</p>
</div></div>
390443
390443