Home: Perl Programming Help: Intermediate:
Identical key names in hash array?



CPS
Novice

Oct 30, 2012, 10:07 AM


Views: 3254
Identical key names in hash array?

Hello,

As you know hash array keys are unique, and in order to retrieve some value you have to provide key name.

I have following hash array:
KEY <---> VALUE
"AAA" 50
"BBB" 40
"CCC" 90
"BBB" 65

As you can see there are same "BBB" keys. However they have different values.

Is it possible to gather both some way ?
Do i need to declare hash array in some special way?

If it's a question for beginners then... sorry :) please move this thread there :)


(This post was edited by CPS on Oct 30, 2012, 10:09 AM)


FishMonger
Veteran / Moderator

Oct 30, 2012, 11:04 AM


Views: 3252
Re: [CPS] Identical key names in hash array?

If a hash key needs to have multiple values, then you need to build it as a HoA (Hash of Arrays).


Chris Charley
User

Oct 30, 2012, 11:53 AM


Views: 3247
Re: [CPS] Identical key names in hash array?

Here is and example of a hash of arrays. The first part creates it and the second part prints it out.

Code
#!/usr/bin/perl 
use strict;
use warnings;

my %data;
while (<DATA>) {
my ($key, $val) = split;
push @{ $data{$key} }, $val;
}

use Data::Dumper; print Dumper\%data;

for my $key (sort keys %data) {
for my $val (@{ $data{$key} }) {
print "$key $val\n";
}
}

__DATA__
AAA 50
BBB 40
CCC 90
BBB 65

It produced the following output.

Code
 
C:\Old_Data\perlp>perl t7.pl
$VAR1 = {
'CCC' => [
'90'
],
'BBB' => [
'40',
'65'
],
'AAA' => [
'50'
]
};
AAA 50
BBB 40
BBB 65
CCC 90



rovf
Veteran

Nov 9, 2012, 1:29 AM


Views: 3128
Re: [CPS] Identical key names in hash array?

You could use Hash::MultiValue from CPAN.