regatta am Freitag, 3. März 2006 21.29:
> Good morning/evening everyone,
>
> I have a hash of data , this hash is very big with dynamic elements
> (strings, numbers, hashes, arrays)
>
> Here is an example
>
> $info{'system'}{'load'}{'1'}
> $info{'system'}{'load'}{'5'}
> $info{'system'}{'load'}{'15'}
> $info{'system'}{'hostid'}
> $info{'system'}{'time'}
> $info{'system'}{'hostname'}
> $info{'system'}{'network'}{'eth0'}{'ip'}
> $info{'system'}{'network'}{'eth1'}{'ip'}
> $info{'system'}{'mount'}{'/'} ==> array (/dev/sda1, 100, 10%, 4220)
>
>
> The size and the data may get changed, so is there any  function that
> can help me to print all the %info data  to be like this :
>
> system.load.1
> system.load.2
> ..
> ..
> system.hostname
> system.network.eth0.ip
> ...
> system.mount././dev/sda1
> system.mount./.100
> system.mount./.10%
> ....
>
> I can't think about a way to do that

Hi Regatta,

Below is a possible way to do it. I'm sure there are modules on cpan.org 
dealing with the problem of building the path of all leaf nodes of a tree.

You have to adapt the script if you also want the values printed out.

hth,
Hans

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


# any nested data structure of hashes, arrays, scalars
#
my %data=(a=>{bb=>1, cc=>[2,3,4,5]}, b=>5, c=>{x=>6, y=>{v=>7,w=>8}});


# recursive sub to build path
#
sub dotted_notation {
  my ($item, $str)[EMAIL PROTECTED];
  if (my $ref=ref($item)) {
    # $item contains nested non-scalar data
    #
    if ($ref eq 'ARRAY') {
      _recursive($item->[$_], $str.($str ? '.' : '').$_)
        for @$item;
    }
    elsif ($ref eq 'HASH') {
      _recursive($item->{$_}, $str.($str ? '.' : '').$_)
        for keys %$item;
    }
    else { warn "'$ref' not supported";}
  }
  else {
    # leaf reached, print out accumulated path
    #
    print "$str\n";
  }
}

dotted_notation(\%data);

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to