Arrays are ideal when you want to store lists which always retain their order, and/or you don't need access to a value through a name. Hashes are ideal when you don't care about the order, but you need to access the data through a known name (key).

In this example, we need to keep the three arrays in order to keep a sequence which is always consistent, so we use an AoA:

my @a = qw(1 2 3); my @b = qw(4 5 6); my @c = qw(7 8 9); my @all = ( \@a, \@b, \@c, ); for my $aref ( @all ){ print $_ for @{ $aref }; print "\n"; }

Outputs:

123 456 789

A hash on the other hand means you want to be able to access the data by name, not by the order in which it is stored:

my %hash = ( a => 1, b => 2, c => 3 ); print "$hash{ a }, $hash{ b }, $hash{ c }\n"; #output: 1, 2, 3

A good example I've found is this... imagine you have a school with a bunch of classrooms that are full of students. If you just want to store a list of students names, put them into an array. However, to find the students within a class, you'll need to specify the name of the classroom to access it. An AoA wouldn't be very handy here, but a HoA sure would:

# define the list of students per each class my @room1_pupils = qw( steve mike melissa ); my @room2_pupils = qw( meredith alexa chris ); # create the school, and assign the student lists to each # hash key my %school = ( room1 => \@room1_pupils, room2 => \@room2_pupils, ); # now you can get a list of students by room name (through # the reference) my @students = @{ $school{ room2 } };

note: I did the assignments the long way because I don't know if OP knows about anonymous vars yet.


In reply to Re: Array of array vs hash by stevieb
in thread Array of array vs hash by rakheek

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.