also, if you have another way to structure this, i would appreciate comments. last time, there were suggestions to use a hash with composite keys. i guess i still don't see its benefit yet.
use strict; use warnings; use Data::Dumper; my $ranges = [ [ { I => 3, }, { I => 4, }, { I => 2, }, { I => 6, }, { I => 9, }, ], [ { I => 3, J => 2, }, { I => 4, J => 3, }, { I => 3, J => 4, }, { I => 3, J => 6, }, { I => 4, J => 0, }, { I => 4, J => 1, }, ], [ { I => 4, J => 3, K => 2, }, { I => 4, J => 3, K => 1, }, { I => 4, J => 2, K => 2, }, { I => 2, J => 3, K => 2, }, { I => 6, J => 2, K => 1, }, ], ]; my $loop =0; foreach my $rngGrp ( @{ $ranges } ) { my $ds; my $f=0; foreach my $rngHash ( @{ $rngGrp } ) { my @rngList = sort keys %$rngHash; my ($ii,$vi,$ij,$vj,$ik,$vk); if ( scalar @rngList == 1 ) { $ii = $rngList[0]; $vi = $rngHash->{$ii}; $ds->[$vi] = "line $f"; } elsif ( scalar @rngList == 2 ) { $ii = $rngList[0]; $vi = $rngHash->{$ii}; $ij = $rngList[1]; $vj = $rngHash->{$ij}; $ds->[$vi]->[$vj] = "line $f"; } elsif ( scalar @rngList == 3 ) { $ii = $rngList[0]; $vi = $rngHash->{$ii}; $ij = $rngList[1]; $vj = $rngHash->{$ij}; $ik = $rngList[2]; $vk = $rngHash->{$ik}; $ds->[$vi]->[$vj]->[$vk] = "line $f"; } $f++; } if ( $loop == 0 ) { $ds->[6] = "new line"; $ds->[9] = "newer line"; } elsif ( $loop == 1 ) { $ds->[4]->[0] = "new line"; $ds->[3]->[6] = "newer line"; } elsif ( $loop == 2 ) { $ds->[2]->[3]->[2] = "new line"; $ds->[6]->[2]->[1] = "newer line"; } $loop++; print "DS = $ds\n"; print Dumper $ds; print "\n\n"; }
note that the $ds variable is NOT outside the outer loop. The outer loop represents both the incremental addition to a multidimensional array as well as the variable number of dimensions.
note the inner loop is composed of two functions; one to build/add to an array and one to overwrite existing indicies. this code is part of a huge program and the accessing and modification is a big part of the program.
previous suggestions worked only for the first array of each range. i failed to emphasize that i need to add new indicies to an already existing array. to me, that makes it hard.
In reply to incremental additions to multidimensional arrays by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |