How would you do it?
Recursively.
#! perl -slw
use strict;
use Data::Dumper::SLC;
sub multiDimInit {
my( $value, $dim ) = ( shift, shift );
return $value unless $dim;
return map{ [ multiDimInit( $value, @_ ) ] } 1 .. $dim;
}
my @multi = multiDimInit( 12345, 2, 2, 2, 2 );
Dump \@multi, 80, *STDOUT;
__END__
P:\test>462436
[
[
[ [ [ '12345', ], [ '12345', ], ], [ [ '12345', ], [ '1234
+5', ], ], ],
[ [ [ '12345', ], [ '12345', ], ], [ [ '12345', ], [ '1234
+5', ], ], ],
],
[
[ [ [ '12345', ], [ '12345', ], ], [ [ '12345', ], [ '1234
+5', ], ], ],
[ [ [ '12345', ], [ '12345', ], ], [ [ '12345', ], [ '1234
+5', ], ], ],
],
]
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
"Science is about questioning the status quo. Questioning authority".
The "good enough" maybe good enough for the now, and perfection maybe unobtainable, but that should not preclude us from striving for perfection, when time, circumstance or desire allow.
| [reply] [d/l] |
Your base case was a level off: your sub guarantees that the bottom level arrays will have one element each. A correction:
sub multiDimInit {
my( $value, $dim ) = ( shift, shift );
return ($value) x $dim unless @_;
return map [multiDimInit( $value, @_ )], 1 .. $dim;
}
Caution: Contents may have been coded under pressure.
| [reply] [d/l] |
Much better++
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
"Science is about questioning the status quo. Questioning authority".
The "good enough" maybe good enough for the now, and perfection maybe unobtainable, but that should not preclude us from striving for perfection, when time, circumstance or desire allow.
| [reply] |
That's so funny - I was going to post the exact same response. :-)
- In general, if you think something isn't in Perl, try it out, because it usually is. :-)
- "What is the sound of Perl? Is it not the sound of a wall that people have stopped banging their heads against?"
| [reply] |
How would you do it?
Since you asked, my answer is "I don't".
I've written a lot of Perl code over the many years. Rarely have I needed to "initialize" anything. Maybe it's the class of problems I solve, but I generally just let autoviv take care of fleshing out my arrays and hashes as I need them.
Letting undef stand in for either an empty string or the zero value is amazingly handy.
| [reply] |
| [reply] |