Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Array consolidating values

by johngg (Canon)
on Oct 07, 2019 at 14:43 UTC ( #11107137=note: print w/replies, xml ) Need Help??


in reply to Array consolidating values

Noting that maikelnight usually provides code with questions, I don't mind cutting a little slack. As 1nickt suggests, iterate over @servers creating a HoA where the key is the "Host" and the value is an anonymous array onto which we push each "GroupName" as it is encountered. I've added another server that is in only one group and also shuffled the @servers array so as to show how to get sorted groups in the output. I also include Data::Dumper output to show the HoA structure. The code:-

use 5.026; use warnings; use Data::Dumper; my @servers = ( { Host => q{server04}, GroupName => q{serversB}, }, { Host => q{server02}, GroupName => q{serversC}, }, { Host => q{server04}, GroupName => q{serversA}, }, { Host => q{server02}, GroupName => q{serversD}, }, { Host => q{server02}, GroupName => q{serversB}, }, { Host => q{server02}, GroupName => q{serversA}, }, { Host => q{server03}, GroupName => q{serversC}, }, { Host => q{server04}, GroupName => q{serversC}, }, ); my %inGroups; foreach my $rhServer ( @servers ) { push @{ $inGroups{ $rhServer->{ Host } } }, $rhServer->{ GroupName + }; } say Data::Dumper ->new( [ \ %inGroups ], [ qw{ *inGroups } ] ) ->Sortkeys( 1 ) ->Dumpxs(); say qq{Server $_ is in groups }, join q{, }, sort @{ $inGroups{ $_ } } for sort keys %inGroups;

The output:-

%inGroups = ( 'server02' => [ 'serversC', 'serversD', 'serversB', 'serversA' ], 'server03' => [ 'serversC' ], 'server04' => [ 'serversB', 'serversA', 'serversC' ] ); Server server02 is in groups serversA, serversB, serversC, serversD Server server03 is in groups serversC Server server04 is in groups serversA, serversB, serversC

I hope this is of interest.

Cheers,

JohnGG

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://11107137]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (5)
As of 2020-06-07 08:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you really want to know if there is extraterrestrial life?



    Results (42 votes). Check out past polls.

    Notices?