in reply to multidimensional arrays

When I dump the $array at the end of every loop iteration, I get the following data structures (I assigned $netlist some value, so one can tell it apart from undef):

$VAR1 = [ undef, undef, 'NETLIST' ]; $VAR1 = [ undef, undef, undef, [ undef, undef, 'NETLIST' ] ]; $VAR1 = [ undef, undef, undef, undef, [ undef, undef, undef, [ undef, undef, 'NETLIST' ] ] ];

Although I agree with shigetsu that this looks kinda weird, it's hard to tell if it is, without you telling us what task you're trying to solve...

Anyhow, the same data structure can be created more succinctly by successively chaining the arrayrefs. This would even work for any dimensionality (btw, why quote the numbers if they're going to be used as numeric indices anyway?):

my $ranges = [ { I => 2 }, { I => 3, J => 2 }, { I => 4, J => 3, K => 2 }, { I => 5, J => 4, K => 3, L => 2 } ]; for my $h ( @$ranges ) { my $array = 'NETLIST'; for my $k (reverse sort keys %$h ) { my $a; $a->[$h->{$k}] = $array; $array = $a; } # ... print Dumper $array; }

Output:

$VAR1 = [ undef, undef, 'NETLIST' ]; $VAR1 = [ undef, undef, undef, [ undef, undef, 'NETLIST' ] ]; $VAR1 = [ undef, undef, undef, undef, [ undef, undef, undef, [ undef, undef, 'NETLIST' ] ] ]; $VAR1 = [ undef, undef, undef, undef, undef, [ undef, undef, undef, undef, [ undef, undef, undef, [ undef, undef, 'NETLIST' ] ] ] ];

Update:   actually, maybe you could also just take advantage of Perl's autovivification feature? For example, the following would create the 3-dimensional one of your examples:

$array->[4]->[3]->[2] = $netlist;

IOW, why create the multidimensional array in advance, if Perl will create it for you as required as soon as you access it, by assigning some value, or reading some element?

Replies are listed 'Best First'.
Re^2: multidimensional arrays
by Anonymous Monk on Jun 10, 2007 at 09:57 UTC
    thanks. your idea of chaining the arrayrefs by working backwards is interesting. i'll try this out.

    the $netlist is actually a data structure also. part of it is populated at the time the multidimensional array is created and the rest of it is populated afterwards.

    the use of multidimensional array was attractive because the "population afterwards" code requires accessing this many times. arrays are easily accessed; hash are not.

      arrays are easily accessed; hash are not.

      I see that you solved your problem, though I'm curious as to know what you meant with this. In fact arrays and hashes are very similar beasts. The main difference from the user's POV being that the former ones have indices wich are natural numbers (but for $[, I know, I know...) and the latter ones generic strings.