If I understand your question correctly then you asking how to use hashes with foreach to avoid mismatches that you would have in your array example?.
If so then here is one example:
use strict;
use warnings;
my %sites = (
a => {
A => {
data_type => [ 'X', 'Y' ],
}
},
b => {
B => {
data_type => [ 'Y', 'Z' ],
}
},
c => {
},
);
for my $site ( keys %sites ) {
for my $server ( keys %{ $sites{ $site } } ) {
for my $data ( keys %{ $sites{ $site }{ $server } } ) {
my @data_types = @{ $sites{ $site }{ $server }{ data_type } };
say "On site $site is server $server with $data @data_types";
}
}
}
You can also use while & each which does produces easier code on the eye:
while ( my ( $site, $site_info ) = each %sites ) {
while ( my ( $server, $server_info ) = each %{ $site_info } ) {
my @data_types = @{ $server_info->{data_type} };
say "On site $site we have server $server with data types @data_types"
if @data_types;
}
}
Also note I removed last loop in above example because its currently superfluous with my example hash data.
NB. If you plan to amend keys or break out of loop then please read up on each and how it affects the iteration.
/I3az/
PS. This example is not about the loop but about data being best represented as a Hash and not an Array! (though its not clear 100% from question that is so!).