CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

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

 



CPS
Novice

Oct 30, 2012, 10:07 AM

Post #1 of 4 (1807 views)
Identical key names in hash array? Can't Post

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

Post #2 of 4 (1805 views)
Re: [CPS] Identical key names in hash array? [In reply to] Can't Post

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

Post #3 of 4 (1800 views)
Re: [CPS] Identical key names in hash array? [In reply to] Can't Post

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

Post #4 of 4 (1681 views)
Re: [CPS] Identical key names in hash array? [In reply to] Can't Post

You could use Hash::MultiValue from CPAN.

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives