Hi Michael,

 

Thanks for your fast reply. I didn't realize that the shift is of
immediate effect not only to the array but also to the current element
of iteration in the loop itself.

 

LG, 
Nora 

 

 

Von: Michael Newman [mailto:newman.michae...@gmail.com] 
Gesendet: Montag, 27. September 2010 09:34
An: HACKER Nora
Betreff: Re: Problem with foreach loop

 

When $arr2 eq '2', you shift  'one' off @arr1, but you're still working
with$ arr[0], which is now 'two'.  When the second foreach ends, it
moves onto $arr1[1], which is 'three'.

Also, if you want it to stop at '2', put a last; after you shift from
@arr1.

        On Sep 27, 2010 3:22 AM, "HACKER Nora" <nora.hac...@stgkk.at>
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;
                       }
               }
        }
        
        produces that result:
        
        oracle:/opt/data/magna/wartung/work/nora> ./test.pl
        Arr1: one
        Arr2: 1
        Arr2: 2
        Arr2: 3
        Arr1: three
        Arr2: 1
        Arr2: 2
        Arr2: 3
        
        whereas I had expected the output to be like this:
        
        oracle:/opt/data/magna/wartung/work/nora> ./test.pl
        Arr1: one
        Arr2: 1
        Arr2: 2
        Arr2: 3
        Arr1: two       # why not?
        Arr2: 1         # why not?
        Arr2: 2         # why not?
        Arr1: three
        Arr2: 1
        Arr2: 2
        Arr2: 3
        
        Thanks in advance!
        
        Regards,
        Nora
        
        
        

Reply via email to