A hash of hashes will do the trick nicely and is infinitely extensible. Here I populate a game board that extends from x = -5 to x = +5 with the same range for y then pluck a value from one square (I store the co-ordinates there for simplicity). Probably the simplest, if not the most memory efficient way to do it.

Hope this helps.

Cheers

tachyon

# declare $grid to hold ref to anon hashes (thanks tye) my $grid; for my $x(-5..5) { for my $y(-5..5) { $grid->{$x}{$y} = "co-ords x:$x, y:$y"; } } print "Here is -2,3 : ", $grid->{-2}{3}; print "\nHere is 0,0 : ", $grid->{0}{0};

If you want to store a range of attributes for each square a super grid made of a hash of hashes will work.

Note this has been modified for efficiency based on tye's post:

my %grid1; for my $x(-5..5) { for my $y(-5..5) { $grid1{$x,$y} = { name => "$x,$y", power => int rand(10), allow => "all" }; } } print "\nHere is name 0,0 : ", $grid1{0,0}{'name'}; print "\nHere is power -2,3 : ", $grid1{-2,3}{'power'}; print "\nHere is allow 5,4 : ", $grid1{0,0}{'allow'};

A hash of hash of arrays is more space efficient but you must index the contents of each square numerically

my %grid2; for my $x(-5..5) { for my $y(-5..5) { $grid2{$x,$y} = ["$x,$y",int rand(10),"all"]; } } print "\nHere is name 0,0 : ", $grid2{0,0}[0]; print "\nHere is power -2,3 : ", $grid2{-2,3}[1]; print "\nHere is allow 5,4 : ", $grid2{0,0}[2];

In reply to Re: 2D Arrays as a Gameboard by tachyon
in thread 2D Arrays as a Gameboard by gregor42

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.