References :: Array of Hashes
Dynamically creating complex data structures during an iterative process is often required and quite easy. Accessing values (iteratively or otherwise) from a complex data structure can be an overwhelmingly pleasant experience.
Generating an Array of Hashes (AoH)
This structure is very common, representing rows extracted from either a text file of columnar data or from an SQL query.
example text file contents:
J.S. Bach, Baroque, 0
Brahms, Romantic, 4
Haydn, Classical, 104
Prokofiev, 20th Century, 7
Schubert, Romantic, 9
Sibelius, 20th Century, 7
Vaughan Williams, 20th Century, 9
Brahms, Romantic, 4
Haydn, Classical, 104
Prokofiev, 20th Century, 7
Schubert, Romantic, 9
Sibelius, 20th Century, 7
Vaughan Williams, 20th Century, 9
1 # declare empty array reference to store our records 2 my $composers = []; 3 4 # parse the file and create array of hashes 5 while (<IN>) 6 { 7 my ($name, $period, $num) = split(/,\s*/, $_); 8 9 # push anonymous hash reference onto the array reference 10 push(@{$composers}, { name => $name, period => $period, num => $num }); 11 }
Accessing an Array of Hashes
Any of the values of the data structure $composers can be easily accessed. Who is the composer in the second element of the array?
1 print $composers->[1]->{'name'};
2
3 # outputs 'Brahms'
And what is the composer's musical period?
1 print $composers->[1]->{'period'};
2
3 # outputs 'Romantic'
Let's print out all composers' names except those from the Romantic period:
1 # curly braces are optional 2 for my $record (@{$composers}) 3 { 4 next if $record->{'period'} =~ /Romantic/o; 5 6 print qq[$record->{'name'}\n]; 7 }