Hi Nora,

On Monday 27 September 2010 09:19:46 HACKER Nora wrote:
> Hello list,
> 
> Could someone please explain why this test script:
> 
> my @arr1 = qw(one two three);
> my @arr2 = qw(1 2 3);
> 
> foreach my $arr1 ( @arr1 ) {
>         print "Arr1: $arr1\n";
>         foreach my $arr2 ( @arr2 ) {
>                 print "Arr2: $arr2\n";
>                 if ( $arr2 eq '2' ) {
>                         shift @arr1;

You shouldn't modify an array (@arr1 in this case) while iterating over it 
using foreach. Otherwise, the results will be unpredictable. One option to 
overcome it is to do:

[code]
my @arr1_copy = @arr1;

while (defined (my $arr1_elem = shift(@arr1_copy)))
{
        # Do something with $arr1_elem
}
[/code]

This will not work properly if @arr1 contains undef elements but it's 
relatively easy to fix:

[code]
while (@arr1_copy)
{
        my $arr1_elem = shift;
}
[/code]

Regards,

        Shlomi Fish

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to