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?
In reply to Re: multidimensional arrays
by almut
in thread multidimensional arrays
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |