On Mon, Sep 27, 2010 at 9:19 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
>
>
>
>

Ok, for starters your output is different from the above listed example. The
actual output is:

Arr1: one
Arr2: 1
Arr2: 2
Arr1: two
Arr2: 2
Arr1: three
Arr2: 3

Which makes a lot of sense, you after all start you loop printing Arr1[0]
then in that same loop you print Arr2[0] and Arr2[1] at which point you
shift Arr2; and leave the inner loop, now you are at the end of your main
loop so you print Arr[1] and again start a new inner loop printing Arr[0]
(which thanks to your shift now is equal to "2" and because this is the case
your if statement again shifts Arr2 and ends the inner loop, back in the
main loop there is nothing more to do so we start the loop again this time
printing Arr1[2] and we enter the inner loop printing Arr2[0] which now is
"3" so the if statement never becomes true and we exit the inner loop, the
main loop has come to the end of the array as well so we exit that and the
code ends.

There is nothing weird about what is happening here. I think that you are
using a few different scripts to test different things and by now your
output and your actual script do not match which causes most of the
confusion.
I found the best way to actually get your head around the most complex loops
is to write/draw them out and get an actual picture of what is happening. If
you look at most modelling technique this is exactly what they do, it is the
best way for a humans brain to process what is going on. ;-)

Anyway to get the result you want you should simply pop your second array
when you encounter a "3" and in that case of course not print...

foreach my $arr1 ( @arr1 ) {
       print "Arr1: $arr1\n";
       foreach my $arr2 ( @arr2 ) {
               if ( $arr2 eq '3' ) {
                       pop @arr2;
               } else {
               print "Arr2: $arr2\n";
              }
       }
}

That will result in:

Arr1: one
Arr2: 1
Arr2: 2
Arr1: two
Arr2: 1
Arr2: 2
Arr1: three
Arr2: 1
Arr2: 2

Regards,

Rob

Reply via email to