Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: Using multi-level hashes

by JamesNC (Chaplain)
on Oct 29, 2005 at 20:58 UTC ( #503911=note: print w/ replies, xml ) Need Help??


in reply to Using multi-level hashes

Here is an example of an oop approach you may find useful.

package component; my %sc; sub new { bless { name => "$_[1]" }, 'component'; } sub name { $_[0]->{name}; } sub sc { $sc{$_[0]->name} = [] unless $sc{$_[0]->name}; push @{$sc{$_[0]->name}}, $_[1]; $_[0]{$_[1]} = new component($_[1]); }; sub label:lvalue { $_[0]->{lbl}; } sub subs { \@{$sc{$_[0]->name}}; } 1; package project; sub new { bless { }, 'project'; } sub components { my @c; @c = sort keys %{$_[0]}; \@c; } sub addcomponent { $_[0]->{$_[1]} = new component( $_[1] ); $_[0]->{$_[1]}; } sub show { my $proj = shift; foreach my $comp ( @{$proj->components} ){ print "$comp\n"; next unless $#{$proj->{$comp}->subs} > 0; foreach my $sc ( @{$proj->{$comp}->subs} ){ next unless $proj->{$comp}{$sc}; print "\t$sc\t" if $sc; print $proj->{$comp}{$sc}->label,"\n" if $proj->{$comp}{$sc}->label; } } } 1; use strict; my $proj = new project(); my $i = 0; while( <DATA> ){ $i++; chomp; next if $i == 1; my ($comp, $subcomp, $label ) = split /\t/, $_; my $sw = $proj->{$comp}; $sw = $proj->addcomponent( $comp ) unless $sw; my $sc = $sw->sc($subcomp); $sc->label = $label; } $proj->show; my $hw = join ', ', @{$proj->{Hardware}->subs}; print "Hardware subcomponents ( $hw )\n"; my $sw = $proj->{Software}; my $db = $sw->{Database}; my $label = $db->label; print "$sw->{name} $db->{name} $label\n"; __DATA__ COMPONENT SUBCOMPONENT LABEL Software Database Test-1.01 Software Good Languages Perl Software Sucky Languages Java Hardware Monitor 19" LCD Hardware CPU Pentium 2.4 Ghz

Cheers,
JamesNC


Comment on Re: Using multi-level hashes
Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://503911]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (5)
As of 2014-10-22 06:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (114 votes), past polls