http://www.perlmonks.org?node_id=1059906


in reply to array of hashes?

Definitely read perldsc as per toolic's advice.

However, your question doesn't seem to match the title; or at least, I'm slow enough without my first cup of coffee this morning that I don't see how you're heading anywhere near an Array of Hashes (hereafter, AoH) with your problem.

Therefore, at the end of this post, I will give you a working example of an AoH in hopes that this will bridge the gap. Absent that, the conversation will hopefully lead us in a useful direction.

What your last paragraph and code suggest is that you are heading toward continued use of your hash as it exists, merely changing the keys based on a switch.

The purpose of an array is to have a list (no pun intended) of items which are simply stacked up and conveniently accessed. Traditionally accessed via their index value ([0] through [n]), Perl stepped up and gave us an indexless way to work through the queue in its most common use case: Sequentially processing each element. Perl's genius addition was the foreachloop.

So an Array of Hashes is a way to stack up a bunch of hashes in one place so they can be accessed without particular attention to how many of them there are, where they can later be processed (likely in a foreach loop).

I am really not making the connection between your description and the need to track multiple hashes from a single point.

Can you clarify? Or is it possible that AoH isn't exactly what you were looking for?

In the meantime, here's a sample use of AoH:

#!/usr/bin/perl use strict; use warnings; # An example of using an array of hashes my @MasterArray = (); my %SubHash1 = ( 'ABC' => 2, 'DEF' => 3, ); my %SubHash2 = ( 'GHI' => 5, 'JKL' => 6, ); my %SubHash3 = ( 'MNO' => 8, 'PQR' => 9, ); # Now use push to append a reference to the hash into the array: push @MasterArray, \%SubHash1; push @MasterArray, \%SubHash2; push @MasterArray, \%SubHash3; # Extract the reference and build a temporary hash to access its eleme +nts: foreach my $ArrayElement (@MasterArray) { print "-----[ New Hash from Array ]---------------\n"; my %CurrentHash = %$ArrayElement; foreach my $CurrentKey (sort keys %CurrentHash) { my $CurrentValue = $CurrentHash{$CurrentKey}; print "Key {$CurrentKey} contains '$CurrentValue'\n"; } } print "-------------------------------------------\n"; exit; __END__

C:\Steve\Dev\PerlMonks\P-2013-10-27@0815-Array-of-Hashes>perl testAoH. +pl -----[ New Hash from Array ]--------------- Key {ABC} contains '2' Key {DEF} contains '3' -----[ New Hash from Array ]--------------- Key {GHI} contains '5' Key {JKL} contains '6' -----[ New Hash from Array ]--------------- Key {MNO} contains '8' Key {PQR} contains '9' -------------------------------------------