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

Greetings Monks,

Looking to some problem I've ran into many times without figuring out.

1) Take a string (or an array) of numbers of any length.
2) For each number, push the number to be an index value (in this case - a MD array).

#!/usr/bin/perl -w use strict; my @number = qw(2 3 4 5); # Get those values to index array element @MDarray[2][3][4][5] = #Do something;
Thanks much, best.

Replies are listed 'Best First'.
Re: Converting string into index MD array
by ikegami (Patriarch) on Jul 17, 2007 at 16:05 UTC
    Data::Diver

    or

    my @indexes = ( 2, 3, 4, 5 ); my $p = \\@MDarray; $p = \($$p->[$_]) for @indexes; $$p = ...;

    Tested.

      Nice... Very compact and avoids having to treat the final index differently than the others, which was one thing I really didn't like about my version.
Re: Converting string into index MD array
by dsheroh (Monsignor) on Jul 17, 2007 at 15:49 UTC
    Untested code, but something along the lines of this should work (I'm assuming @MDarray is already defined):
    my @number = qw(2 3 4 5); my $curr_array = \@MDarray; while ($#number > 0) { # Stop when 1 element left my $index = shift @number; $curr_array = @$curr_array[$index]; } @$curr_array[$number[0]] = # Do something
    Since multi-dimensional arrays in Perl are just arrays of arrayrefs (of arrayrefs of...), this starts with a reference to the top-level array, then walks down through each level, getting the reference to the next level, until it reaches the end.
      Works, thanks (tested).
      Frank