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


Oct 30, 2012, 10:07 AM

Views: 3555
Identical key names in hash array?


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:
"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)

Veteran / Moderator

Oct 30, 2012, 11:04 AM

Views: 3553
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

Oct 30, 2012, 11:53 AM

Views: 3548
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.

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

AAA 50
BBB 40
CCC 90
BBB 65

It produced the following output.

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


Nov 9, 2012, 1:29 AM

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

You could use Hash::MultiValue from CPAN.