I believe this is your question:
"I have an array (@data_list) containing hash references. Each hash reference contains two keys, 'key' and 'value'. I want to turn this into one hash containing 'key'=>'value' pairs. How can I do this?"
My solutions below assume that you have unique key values, or are un-interested in collisions. In the case of a collision, the last reference to the key wins.
Here is a fully verbose version:
my %final_hash;
foreach my $data_pair ( @data_list)
{
$key = $data_pair->{ key };
$value = $data_pair->{value};
$final_hash{ $key } = $value;
}
use Data::Dumper;
print Dumper \%final_hash;
A shorter version:
my %final_hash =
map { $_->{key} => $_->{value} }
@data_list;
#verify the output
use Data::Dumper;
print Dumper \%final_hash;
And how do we know they work? We test them.
Full version with tests:
#!/usr/bin/perl -w
use strict;
use Data::Dumper;
use Test::More tests => 2;
my @data_list = (
{ key => 'correct', value => 'AAA' },
{ key => 'correction', value => 'BBB' },
{ key => 'date', value => '20090303' },
{ key => 'date', value => '20090308' },
);
my $expected = {
correct => 'AAA',
correction => 'BBB',
date => '20090303',
date => '20090308',
};
my %final_hash_long;
foreach my $data_pair (@data_list) {
my $key = $data_pair->{key};
my $value = $data_pair->{value};
$final_hash_long{$key} = $value;
}
my %final_hash_short =
map { $_->{key} => $_->{value} } @data_list;
is_deeply( \%final_hash_long, $expected, "long version works" );
is_deeply( \%final_hash_short, $expected, "short version works" );
|