note
neniro
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:
<code>
#!/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', position => 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;
</code>
552989
552989