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

the following code compares the sequences $s and $t and calculates a 2-dim matrix containing the lengths of matching substrings at the position of the last matching characters. I don't know how to dereference in the nested foreach loop at the bottom in order to go through the matrix scalar by scalar.
$s = "evian-eauminerale"; $t = "borisvian-ecrivain"; foreach my $i (1..length($s)) { foreach my $j (1..length($t)) { if (substr($s, $i-1, 1) eq substr($t, $j-1, 1)) { $M[$i][$j] = $M[$i-1][$j-1]+1; $M[$i-1][$j-1] = 0; } } } foreach @array (@M) { foreach $element (@array) { print "$element "; } print "\n"; }

Replies are listed 'Best First'.
Re: multi-dimensional arrays, dereferencing
by thinker (Parson) on Aug 08, 2003 at 10:14 UTC

    Hi fabalicious

    If @M is an array of array references, then

    foreach $arrayref (@M) { foreach $element (@$arrayref) { print "$element "; } print "\n"; }

    hope this helps

    cheers

    thinker

Re: multi-dimensional arrays, dereferencing
by Skeeve (Parson) on Aug 08, 2003 at 10:12 UTC
    #untested! foreach $aref (@M) { foreach $element (@$aref) { print "$element "; } print "\n"; }
Re: multi-dimensional arrays, dereferencing
by thinker (Parson) on Aug 08, 2003 at 12:12 UTC

    Hi fabalicious

    As an aside, and this is merely a matter of style, your method of doing what you want to do is very verbose.

    I would choose to write it as

    print "@$_\n" for @M;

    taking advantages of some of some not so intuitive Perl idioms, like using @$_ to dereference each array, and the fact that "@array" will join the elements of @array with $", which is a space by default. And it saves you printing an extra space character at the end of each line :-)

    In the spirit of TMTOWTDI

    cheers

    thinker

Re: multi-dimensional arrays, dereferencing
by fabalicious (Novice) on Aug 08, 2003 at 10:23 UTC
    Cheers to skeeve and thinker. Still doesn't look very obvious to me, but it does the job.

      Hi fabalicious

      For a good explaination, see

      perldoc perllol perldoc perlreftut

      hope this helps

      cheers

      thinker

        I would add

        perldoc perldsc

        And it happens that the free online chapter from merlyn's new book Learning Perl Objects, References and Modules covers this very topic. Check it out on the O'Reilly website.

        NB: that shouldn't stop you from buying the book :-)

        dave

      An "array of arrays" is in fact an array of references to arrays. So each element of your @M is an array reference leading us to:
      foreach $aref (@M) {...
      To get the actual array from an array reference, one usually writes @$aref leading us to
      foreach $element (@$aref) {...
      and that's all about it.