Senthil kumar
Senthil kumar

Reputation: 993

In Perl how do you create and use an array of hashes?

How to do a Perl program that contains an array and that array points a hash?

It is like this pictorially,

(M1)        (M2)        ...it goes on
 |--k1=>v1   |--K1=>v1
 |--k2=>v2   |--k2=>v2

I should access that array M1, then the hash it contains inside. (and so on)...

Upvotes: 3

Views: 1349

Answers (5)

Dave Cross
Dave Cross

Reputation: 69224

In the interests of teaching you to fish, here's a link to the Perl data structures cookbook (perldsc) on building complex data structures in Perl.

Upvotes: 1

Jonathan Leffler
Jonathan Leffler

Reputation: 753465

This should do it - though it isn't quite clear to me how you wanted 'M1' and 'M2' to play into the scenario:

my(@array) = ( { k1 => "v1", k2 => "v2" }, { K1 => "V1", K2 => "V2" } );

print "$array[0]->{k1}\n";
print "$array[1]->{K2}\n";

You are making your life more interesting when you use different sets of keys in the different elements of the array (k1 and k2 versus K1 and K2). That's far from forbidden, but it makes the processing harder.

Upvotes: 5

codaddict
codaddict

Reputation: 454920

Something like:

%h1 = ('a'=>'abc','b'=>'bcd'); # hash 1
%h2 = ('A'=>'Abc','B'=>'Bcd'); # hash 2
@arr = (\%h1,\%h2); # array of hash references.
foreach $hash_ref (@arr) { # iterate through the array.
        foreach $key(keys %$hash_ref) { # iterate through the hash.
                print $key.' '.$$hash_ref{$key}."\n"; #print key => value
        }   
}

Upvotes: 1

Eugene Yarmash
Eugene Yarmash

Reputation: 149726

You need to use hash references:

my @array;    
push @array, { k1=>"v1", k2=>"v2" }, { k1=>"v1", k2=>"v2" };

Then, access the hashes like this:

my $val = $array[0]{k1};

Upvotes: 4

user181548
user181548

Reputation:

You need a hash reference, as marked by { } below.

my @array = ({ k1 => "v1", k2 => 'v2' }, { K1 => 'V1', });

Upvotes: 0

Related Questions