in reply to Perl For loops

This code doesn't need to be so complicated - for instance why is there an and in there? If the values are always simple integers then the whole $z thing is just testing for equality with 0.

Given that, the loop is just aborting once a 0 values is hit. We also know that the length of the outer array in the result is the count of the first inner array in the matrix. Thus:

my @matrix=([qw(1 2 4 4)],[qw(5 2 0 8)],[qw(9 10 11 12)],); my @t; for my $i (0..$#{$matrix[0]}) { for my $j (0..$#matrix) { last if $matrix[$j][$i] == 0; $t[$i][$j] = $matrix[$j][$i]; } }
The result of both your code and mine is the same:

$VAR1 = [ [ 1, 5, 9 ], [ 2, 2, 10 ], [ 4 ], [ 4, 8, 12 ], ]
Update: I must have missed Util's comment, which is virtually identical to mine :)

Replies are listed 'Best First'.
Re^2: Perl For loops
by atemon (Chaplain) on Jul 04, 2007 at 07:31 UTC

    Hi Monks,

    I don't know what is the purpose of getting it in a "for" loop. But if we are concerned only about output or $t, can't we do something like
    $t = [ @matrix ]
    so that the entire program would be
    my @matrix=([qw(1 2 4 4)],[qw(5 2 0 8)],[qw(9 10 11 12)],); my $t = [ @matrix ];
    Or even simpler like
    my $t = [ [qw(1 2 4 4)],[qw(5 2 0 8)],[qw(9 10 11 12)], ];
    cheers!

    -VC

    Update: Appologies for the carelessness & waste of time.

      well, because your way $t is:
      [ [ 1, 2, 4, 4 ], [ 5, 2, 0, 8 ], [ 9, 10, 11, 12 ], ]
      when it should be:
      [ [ 1, 5, 9 ], [ 2, 2, 10 ], [ 4 ], [ 4, 8, 12 ], ]
      kinda different...