Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...