Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: Multidimensional Arrays

by Anonymous Monk
on Nov 25, 2004 at 09:29 UTC ( #410358=note: print w/ replies, xml ) Need Help??


in reply to Multidimensional Arrays

my @row0 = (1, 0, 0); my @row1 = (0, 1, 0); my @row2 = (0, 0, 1); my @arr = ( \@row0, \@row1, \@row2 ); for ( $i = 0; $i < 3; $i++ ) { for ( $j = 0; $j < 3; $j++ ) { print "arr[$i][$j] = $arr[$i][$j]\n"; } } # works perfectly print "*" x 80, "\n"; my @another = \$arr[1]; for ( $i = 0; $i < 3; $i++ ) { print "another[$i] = $another->[$i]\n"; } # while this loop prints blanks
what am i doing wrong ?


Comment on Re: Multidimensional Arrays
Download Code
Replies are listed 'Best First'.
Re^2: Multidimensional Arrays
by chb (Deacon) on Nov 25, 2004 at 10:02 UTC
    You could try:
    my @another = @{$arr[1]}; for ( $i = 0; $i < 3; $i++ ) { print "another[$i] = $another[$i]\n"; }
    using an array to hold the row, or:
    my $another = $arr[1]; for ( $i = 0; $i < 3; $i++ ) { print "another[$i] = $another->[$i]\n"; }
    using a ref to the row. You should also consider use strict;, BTW...
Re^2: Multidimensional Arrays
by wfsp (Abbot) on Nov 25, 2004 at 10:12 UTC
    my @another = \$arr[1];

    @another has a single element - a reference to a reference to an array.

    Try:

    ${${$another[0]}}[$i]

    Update: fixed typo

      This works, too:
      @{${$another[0]}}[$i]
      I think ist is a little bit clearer (from in to out): 1. fetch array element 0, 2. dereference, 3. treat it like an array, 4. fetch via [$i].

      But this all looks really ugly. It would be better to fix the strange assignment to @another than to use such a complicated expression just to fetch a value...

        You're right.

        I find Perl's data structures very useful but often get into a tangle with them. The main reason I had a go at the OP's question was to see if I could fathom it out. I was so pleased when I actually got something to work I couldn't resist the urge to show off!

        I must now confess that I dereferenced it in stages first using temps. This is what I usually do myself if only so that I can still understand it the following day.

        ++ to you for being helpful rather than trying to be clever. My bad!

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://410358]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (19)
As of 2015-07-31 21:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (282 votes), past polls