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...


In reply to Re^3: multidimensional arrays by blazar
in thread multidimensional arrays by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.