开发者

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开发者_Python百科 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)...


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.


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};


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
        }   
}


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.


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜