Hash of hash in perl

  • Thread starter Shashank Khanvilkar
  • Start date
S

Shashank Khanvilkar

Hi,
Any help is appreciated.
I have data in the following format

A
B=2
C=3
B
S=2
T=10
....


I need to populate a hash data structure (%graph) in perl so that %graph
will have the form
%graph = (

A => {B=>2,C=>3},

B => {S=>2,T=>10}
}

Assume that I have a program that has read A in $A, B in $B and so on
and the integers in $int. Can I Do the following:

%graph{$A}{$B} = $int

to populate the above hash of the hash.
Thanks
Shashank
 
J

Janek Schleicher

I have data in the following format

A
B=2
C=3
B
S=2
T=10
...


I need to populate a hash data structure (%graph) in perl so that %graph
will have the form
%graph = (

A => {B=>2,C=>3},

B => {S=>2,T=>10}
}

What have you tried so far? It's hard to spot where's your problem without
to know something about.

However the following snippet seems to do what you want:

#!/usr/bin/perl
use strict;
use warnings;

my %graph;
my $sec;

while (<DATA>) {
chomp;
/^(\w+)/ and $sec = $1
or /(\w+)=(\d+)/ and $graph{$sec}->{$1} = $2;
}

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

__DATA__
A
B=2
C=3
B
S=2
T=10


Greetings,
Janek
 
G

gumby

Shashank Khanvilkar said:
Hi,
Any help is appreciated.
I have data in the following format

A
B=2
C=3
B
S=2
T=10
...


I need to populate a hash data structure (%graph) in perl so that %graph
will have the form
%graph = (

A => {B=>2,C=>3},

B => {S=>2,T=>10}
}

Assume that I have a program that has read A in $A, B in $B and so on
and the integers in $int. Can I Do the following:

%graph{$A}{$B} = $int

to populate the above hash of the hash.
Thanks
Shashank

If you could give an example snipit of the code you are writing to
show how you are using the hash of hash.
I use these alot.

The question will this work ?
%graph{$A}{$B} = $int
Yes but you should do it like this
$graph{$A}{$B} = $int;
Extracting the keys might be the only speed bump.
my @akeys = keys %graph;
my @bkeys = keys % {$graph{$A}};

Hope this helps
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top