in reply to Array of array vs hash

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.

Replies are listed 'Best First'.
Re^2: Array of array vs hash
by rakheek (Sexton) on May 15, 2012 at 19:12 UTC
    Thanks! that was helpful.