in reply to Re^2: Not sure how to populate a hash
in thread Not sure how to populate a hash

Hello aditya1977,

In the spirit of TMTOWTDI, here’s a concise implementation of LanX’s hash slice solution:

#! perl use strict; use warnings; use Data::Dump; my %nodemetrics; my @nodelist = qw(server1 server2); my @attributes = qw(memory cpu disk network); my $string = '1024|2200|30|100'; my @data = split /\|/, $string; @{ $nodemetrics{$_ } }{@attributes} = (0) x @attributes for @node +list; dd \%nodemetrics; @{ $nodemetrics{server1} }{@attributes} = @data; dd \%nodemetrics;

Output:

22:03 >perl 1027_SoPW.pl { server1 => { cpu => 0, disk => 0, memory => 0, network => 0 }, server2 => { cpu => 0, disk => 0, memory => 0, network => 0 }, } { server1 => { cpu => 2200, disk => 30, memory => 1024, network => 100 + }, server2 => { cpu => 0, disk => 0, memory => 0, network => 0 }, } 22:03 >

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Replies are listed 'Best First'.
Re^4: Not sure how to populate a hash
by aditya1977 (Novice) on Sep 24, 2014 at 13:23 UTC

    Thanks so much for your help guys. I mostly get this now!

    Just one last question. If I wanted to return the attributes of one of the servers as a hash, how do I get to that data?

    So in other words, I want to a create a simple hash %server_properties which name value pairs of one of the servers?

      This creates a copy (NOT an alias i.e. writing to it won't change the original data)

       %server_properties = %{$nodemetrics{server1}}

      Otherwise

      $h_server1 = $nodemetrics{server1}

      (like already shown) is the same hashref, which can be safely changed

      $h_server1->{cpu}=100 or alternatively $$h_server1{cpu}=100

      see perlref and perldsc for details!

      Cheers Rolf

      (addicted to the Perl Programming Language and ☆☆☆☆ :)