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

Hi aditya1977

Lets try this one.

use strict; use warnings; use Data::Dumper; my %nodemetrics; my @nodelist = qw(server1 server2); my @system_attributes = qw(memory cpu disk network); # Initialise the hash with zeros my ($node); foreach $node (@nodelist) { foreach (@system_attributes){ $nodemetrics{$node}{$_} = 0; } } print Dumper(\%nodemetrics); my $string="1024|2200|30|100"; my @data = split(/\|/,$string); my @keys = keys %{$nodemetrics{'server1'}}; my $hashref = $nodemetrics{'server1'}; @$hashref{@keys}=@data; $nodemetrics{'server1'}=$hashref; print Dumper (\%nodemetrics);

All is well

Replies are listed 'Best First'.
Re^4: Not sure how to populate a hash
by Monk::Thomas (Friar) on Sep 24, 2014 at 12:02 UTC
    my @keys = keys %{$nodemetrics{'server1'}};
    in a somewhat recent perl this leads to:
    $ perl scratch.pl [...] 'server1' => { 'memory' => '1024', 'network' => '2200', 'cpu' => '30', 'disk' => '100' }, [...] $ perl scratch.pl [...] 'server1' => { 'disk' => '1024', 'memory' => '2200', 'cpu' => '30', 'network' => '100' } [...]

    OUCH!!

    You already have the keys in the correct order available, why not use that?

    my @system_attributes = qw(memory cpu disk network); [...] my $hashref = $nodemetrics{'server1'}; @$hashref{@system_attributes}=@data;