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:-