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

Re: Help with Hash of hashes, is there a better way?

by neniro (Priest)
on Jun 01, 2006 at 09:17 UTC ( #553002=note: print w/ replies, xml ) Need Help??


in reply to Help with Hash of hashes, is there a better way?

You could use Objects instead of plain hashes. A few weeks ago i wrote an example for someone with a similar problem. It uses Moose for OO, and you can see how it simplifies the stringification of a nested structure:

#!/usr/bin/perl use strict; use warnings; use Data::Dumper; package SingleState; use Moose; has 'state' => (isa => 'Value', is => 'rw'); has 'value' => (isa => 'Value', is => 'rw'); has 'position' => (is => 'rw'); sub to_s { my $self = shift; return $self->state . "\t=>\t" . $self->value . "\n"; } package Stat; use Moose; has 'states' => (isa => 'ArrayRef', is => 'rw'); has 'title' => (is => 'rw'); has 'position' => (is => 'rw'); sub add_state { my $self = shift; return unless @_; push @{$self->{states}}, $_ for @_; } sub to_s { my $self = shift; my $o = $self->title ? "== " . $self->title . " ==\n" : ''; $o .= $_->to_s for (sort { $a->position <=> $b->position } @{$self +->states}); return $o; } package StatSet; use Moose; use Data::Dumper; has 'stats' => (isa => 'ArrayRef', is => 'rw'); sub add_stat { my $self = shift; return unless @_; push @{$self->{stats}}, $_ for @_; } sub report { my $self = shift; my $s; $s .= $_->to_s . "\n" for (sort { $a->position <=> $b->position } +@{$self->stats}); return $s; } package main; my $set = new StatSet; my $stat1 = new Stat ( title => 'CPU' ); my $stat2 = new Stat ( title => 'Memory' ); my $state1 = new SingleState( state => 'Idle', value => '92', position + => 1 ); my $state2 = new SingleState( state => 'User', value => '0', position + => 2 ); my $state3 = new SingleState( state => 'Cached', value => '531976', po +sition => 1 ); $stat1->add_state( $state1, $state2 ); $stat1->position(1); $stat2->add_state( $state3 ); $stat2->position(2); $set->add_stat($stat1); $set->add_stat($stat2); print $set->report;


Comment on Re: Help with Hash of hashes, is there a better way?
Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (5)
As of 2015-07-30 04:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (269 votes), past polls