Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
266 views
in Technique[技术] by (71.8m points)

arrays - How to create hash with duplicate keys

Now i am modifying the code a little I am using the code for creating hash haivng duplicate keys. Its giving the syntax error.

use strict;
use warnings;
my $s = "12   A    P1  
23   B    P5
24   C    P2
15   D    P1
06   E    P5";
my $hash;
my @a  = split(/
/, $s);
foreach (@a)
{
  my $c = (split)[2];
  my $d = (split)[1];
  my $e = (split)[0];
  push(@{$hash->{$c}}, $d);
}
print Dumper($hash );

i am getting the output as

    $VAR1 = {
          'P5' => [
                    'B',
                    'E'
                  ],
          'P2' => [
                    'C'
                  ],
          'P1' => [
                    'A',
                    'D'
                  ]
        };

But i want the output like

    $VAR1 = {
      'P5' => {
      'E' => '06',
      'B' => '23'
     },
     'P2' => {
      'C' => '24'
    },
    'P1' => {
      'A' => '12',
      'D' => '15'
      }
     };

How to do that

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You hash declaration is incorrect, it should be:

my %hash = ();

or simply:

my %hash;

Then the rest of your code is both too complex and incorrect.

foreach (@a) {
  my ($k, $v) = (split);
  push @{$hash{$k}}, $v;
}

should be enough. See Autovivification for why this works.

With your code, the first time you see a key, you set $hash{$k} to be a scalar. You can't then push things to that key - it needs to be an array to begin with.

The if (-e $hash{$c}) test is wrong. -e is a file existence test. If you want to know if a hash key exists, use:

if (exists $hash{$c}) { ... }

And print %hash; won't do what you expect (and print %{$hash}; is invalid). You'll get a prettier display if you do:

use Data::Dumper;
print Dumper(\%hash);

(Great debugging too, this Data::Dumper.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...