> Programming Languages > Perl
Various Topics Home | Disclaimer | Report Adult Posts

Various Topics on Perl



Perl - "Hash of hash in perl" in Programming Languages


Old 11-18-2004   #1
..asha.. ..anvilk..
 
Default Hash of hash in perl

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}
}

***ume 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
 
Old 11-18-2004   #2
..n.. ..hleich..
 
Default Re: Hash of hash in perl

On Wed, 17 Nov 2004 16:08:07 -0600, Shashank Khanvilkar wrote:

> 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:umper;
print Dumper(\%graph);

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


Greetings,
Janek
 
Old 11-18-2004   #3
..d ..Clell..
 
Default Re: Hash of hash in perl

Shashank Khanvilkar <shashank@mia.ece.uic.edu> wrote:

> Can I Do the following:
>
> %graph{$A}{$B} = $int



What happened when you tried it?


--
Tad McClellan SGML consulting
tadmc@augustmail.com Perl programming
Fort Worth, Texas
 
Old 11-18-2004   #4
..m..
 
Default Re: Hash of hash in perl

Shashank Khanvilkar <shashank@mia.ece.uic.edu> wrote in message news:<cngjth$7h1$1@newsx.cc.uic.edu>...
> 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}
> }
>
> ***ume 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
 

Thread Tools
Display Modes





Powered by vBulletin®
Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.3.0