Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

hash

perl

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)...

like image 682
Senthil kumar Avatar asked Nov 20 '25 16:11

Senthil kumar


2 Answers

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.

like image 140
Jonathan Leffler Avatar answered Nov 23 '25 09:11

Jonathan Leffler


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};
like image 27
Eugene Yarmash Avatar answered Nov 23 '25 07:11

Eugene Yarmash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!