Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Ok, this is probably a silly question, but from the following code how do I reference a row and column value, and change the value, and or print a value:
my @matrix = ( [qw( . . . 1 0 0 1 0 1 0 1)], [qw( . . 0 1 2 3 4 5 6 7 8)], [qw( . 0 . . . . . . . . .)], [qw( 0 1 . . . . . . . . .)], [qw( 1 2 . . . . . . . . .)], [qw( 0 3 . . . . . . . . .)], [qw( 1 4 . . . . . . . . .)], [qw( 1 5 . . . . . . . . .)], [qw( 0 6 . . . . . . . . .)], [qw( 1 7 . . . . . . . . .)], [qw( 1 8 . . . . . . . . .)], [qw( 0 9 . . . . . . . . .)], [qw( 1 7 . . . . . . . . .)], ); foreach $row (@matrix) { print "@$row\n"; }
thanks for the help

Replies are listed 'Best First'.
Re: Array of Array Row Reference
by strat (Canon) on Mar 04, 2002 at 14:51 UTC
    Well, you've got a two-dimensional array, which in perl is a list () of references to lists [].
    If you want to get the element 0/4, just write:
    my $element = $matrix[0]->[4]; # or by shorthand: my $element2 = $matrix[0][4];
    If you want to change the element 6/3 to 8, just write
    $matrix[6]->[3] = 8; # or the same shorthand as above
    If you want go get the whole row number 6:
    my @row6 = @{ $matrix[6] }; # to a list my $listRef6 = $matrix[6]; # to a listreference
    If you want to print this array formatted, you could also do the following:
    foreach my $row (@matrix) { print join ("\t", @$row); }
    Further information gives you: perldoc perllol

    Best regards,
    perl -le "s==*F=e=>y~\*martinF~stronat~=>s~[^\w]~~g=>chop,print"

(jeffa) Re: Array of Array Row Reference
by jeffa (Bishop) on Mar 04, 2002 at 14:44 UTC
    Using the code you have, this snippet will print the fourth column from the second row:
    print $matrix[1]->[3], "\n";

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    

      Using the code you have, this snippet will print the fourth column from the second row: print $matrix[1]->[3], "\n";

      Which can also be written as print $matrix[1][3], which is more multi-dimensional-array-like.

      ++ vs lbh qrpbqrq guvf hfvat n ge va Crey :)
      Nabgure bar vs lbh qvq fb jvgubhg ernqvat n znahny svefg.
      -- vs lbh hfrq OFQ pnrfne ;)
          - Whreq
      

Re: Array of Array Row Reference
by joealba (Hermit) on Mar 04, 2002 at 14:41 UTC