in reply to getting array value from anonymous hash

To access the anonymous array, begin by subscripting: $hashref->{Inventory}{host}. That gives you a reference to the array; you can then dereference it by putting it inside @{ ... }. So:

#! perl use strict; use warnings; use Data::Dump; my $hashref = { Inventory => { lb => 'abc', host => [ { hostA => { os => 'Linux', location => 'Dublin' + } }, { hostB => { os => 'Windows', location => 'US' + } }, { hostC => { os => 'Ubuntu', location => 'Germany +' } }, ], }, }; # Question 1 my @hosts = map { (keys %$_)[0] } @{ $hashref->{Inventory}{host} }; dd \@hosts; # Question 2 push @{ $hashref->{Inventory}{host} }, { hostD => { os => 'Unix', location => 'France' } }; dd $hashref;

Output:

0:39 >perl 871_SoPW.pl ["hostA", "hostB", "hostC"] { Inventory => { host => [ { hostA => { location => "Dublin", os => "Linux" } }, { hostB => { location => "US", os => "Windows" } }, { hostC => { location => "Germany", os => "Ubuntu" } }, { hostD => { location => "France", os => "Unix" } }, ], lb => "abc", }, } 0:39 >

Hope that helps,

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

Replies are listed 'Best First'.
Re^2: getting array value from anonymous hash
by sunil9009 (Acolyte) on Feb 14, 2014 at 02:45 UTC

    Thanks that helped. However am confused with the following code

    my @hosts = map { (keys %$_)[0] } @{ $hashref->{Inventory}{host} };
    { (keys %$_)[0] }

    can be replaced simply with

     { keys %$_ }

    I am not sure what

    $_)[0]

    actually does

      Hello sunil9009,

      You are correct. If you know that each anonymous hash in the array contains exactly one key, then

      my @hosts = map { keys %$_ } @{ $hashref->{Inventory}{host} };

      is all you need. My concern was that the anonymous hash might be expanded to contain multiple keys. My idea was to ensure you get only the first key, by specifying the zero-subscript element of the list returned by keys %$_. But my “solution” doesn’t work, because the order of keys in a hash is unpredictable. To be on the safe side, I should have used something like:

      my @hosts = grep { /^host/ } map { keys %$_ } @{ $hashref->{Inventory} +{host} };

      Hope that helps,

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