in reply to Re^2: multidimensional arrays
in thread multidimensional arrays

interestingly, the problem is CREATING the Ndim array in a general manner. most examples show loops to build each dimension, each nested loop is one dimension.

I don't really think so. It all really depends on how you want to fill it. For example, suppose you just want to create a n-dimensional m x m x ... x m array(-ref) filled with 1's. Then it can be just as simple as in the following example:

#!/usr/bin/perl -l use strict; use warnings; use Data::Dumper; sub ndim { my ($n,$m) = @_; return [(1) x $m] if $n==1; [map [@{ ndim($n-1,$m) }], 1..$m]; } $Data::Dumper::Indent=0; print Dumper ndim @$_ for [1,3], [2,2], [2,3], [3,3]; __END__

Of course this is much ref-deref madness so I would probably use a helper sub instead, at the expense of some extra verbosity:

sub _ndim { my ($n,$m) = @_; return (1) x $m if $n==1; map [_ndim($n-1,$m)], 1..$m; } sub ndim { [_ndim @_] }

(Incidentally, how tempted I would be to put _ndim inside ndim... if only it were not for the "Variable "%s" will not stay shared" gotcha - and yes, I'm aware of the ways round... most of all I'd like lexical named subs, though!)

Just as obviously, I wouldn't use anything like that in a real situation, but it was just to convey an idea...