in reply to duplicate keys on hash
you're supposed to use hash references into arrays?
The data structure you're probably looking for is a hash, where each value is a reference to an individual array - a "hash of arrays". The links that Happy-the-monk provided above should explain.
But I don't see how(in example) typing in the "2" would pull up both BBB AND EEE
"Access and Printing of a HASH OF ARRAYS" in perldsc shows you some examples of how to access the data structure. It'd probably also be helpful to you if you learn about how to handle references in general, e.g. perlreftut.
To get you started, here's one way to build such a structure from the input you showed. One important concept here is autovivification, which is what causes you to be able to write @{$data{$k}} and have a reference to a new array spring into existence ("vivify") even if $data{$k} was previously undefined.
use warnings; use strict; my %data; while (<DATA>) { chomp; next unless /\S/; my ($k,$v) = /^\s*(\S+)\s+(.+?)\s*$/; push @{$data{$k}}, $v; } use Data::Dumper; print Dumper(\%data); __DATA__ 1 AAA 2 BBB 3 CCC 4 DDD 2 EEE
Output:
$VAR1 = { '3' => [ 'CCC' ], '1' => [ 'AAA' ], '4' => [ 'DDD' ], '2' => [ 'BBB', 'EEE' ] };
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: duplicate keys on hash
by Happy-the-monk (Canon) on Feb 11, 2015 at 13:21 UTC |