Every now and then I need to create a n-dimensional array from some given formula, where n almost always is 1 or 2.
I've been searching for a module providing such functionality without success. It would be a surprise if there really wasn't such a thing.

But so I rolled my own and came to this:

# arg_1 to arg_n specify size in dimension k, # last arg is a reference to a sub # - expecting n arguments x1 ... xn # - returning the desired value at $na->[x1]...[xn] sub narray { my $size = shift; my $val = pop; my $na; for my $i (0 .. $size - 1) { $na->[$i] = @_ ? narray(@_, sub {&$val($i, @_)}) : &$val($i); } $na; }
which can be used in various ways and is not limited in dimension:
$ar = narray(3, sub {$_[0]}); # [0, 1, 2] $mr = narray(3, 3, sub {$_[0] == $_[1] || 0}); # [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
just to get an idea.

Does anybody know of a module providing something similar?
Otherwise: Is this of use for someone else or would it even fit into something existing?

UPDATE 1: This would be more perlish if the sub ref argument came first and the sub itself was prototyped:

sub narray (&@); $ar = narray {$_[0]} 3;

UPDATE 2: Incorporating LanX's suggestion of using map into UPDATE 1 results in:

sub narray (&@); sub narray (&@) { my $val = shift; my $size = shift; [map {my $i = $_; @_ ? narray {&$val($i, @_)} @_ : &$val($i)} (0 . +. $size - 1)]; } my $na = narray {"<@_>"} 3, 2 # [['<0 0>', '<0 1>'], ['<1 0>', '<1 1>'], ['<2 0>', '<2 1>']]

Greetings,
-jo

$gryYup$d0ylprbpriprrYpkJl2xyl~rzg??P~5lp2hyl0p$

In reply to n-dim array generator by jo37

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.