Nitesh
Nitesh

Reputation: 157

How to create hash of hash key

I have the following code

use strict;
use warnings;
use Data::Dumper;

my $s = "12   A    P1  
23   B    P5
24   C    P2
15   D    P1
06   E    P5 ";
my $hash = {};
my @a  = split(/\n/, $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

    $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'
 }
  };

Please help.

Upvotes: 1

Views: 221

Answers (2)

TLP
TLP

Reputation: 67900

You need to use a hash if you want a hash as output.

No need to split three times and use postscripts, just split once and assign all variables. Also no need to initialize a scalar as an empty hash, perl will take care of that for you.

I renamed the variables for increased readability.

my $string = "12   A    P1  
23   B    P5
24   C    P2
15   D    P1
06   E    P5 ";
my $hash;
my @lines = split(/\n/, $string);

foreach (@lines)
{
    my ($value, $key2, $key) = split;
    $hash->{$key}{$key2} = $value;
}
print Dumper($hash );

Be aware that if you have multiple values with the same keys, they will overwrite each other. In that case, you'd need to push the values onto an array instead:

push @{$hash->{$key}{$key2}}, $value;

Upvotes: 3

vstm
vstm

Reputation: 12537

Well it's not that different from what you have. Just replace the push with a hash-assign (thank you auto-vivification):

foreach (@a)
{
    my ($e, $d, $c) = split;
    $hash->{$c}->{$d} = $e;
}

Additionally I have re-arranged the "split" so that it's just called once per line.

Upvotes: 1

Related Questions