A function produces this hash of arrays:
<code>'KEYNAME1' => ARRAY(0x1edeeb0)
0 'val11'
1 'val12'
2 'val13'
'KEYNAME2' => ARRAY(0x1efacb8)
0 'val21'
1 'val22'
2 'val23'
</code>
<code>'KEYNAME1' => ARRAY(0x1edeeb0)
0 'val11'
1 'val12'
2 'val13'
'KEYNAME2' => ARRAY(0x1efacb8)
0 'val21'
1 'val22'
2 'val23'
</code>
'KEYNAME1' => ARRAY(0x1edeeb0)
0 'val11'
1 'val12'
2 'val13'
'KEYNAME2' => ARRAY(0x1efacb8)
0 'val21'
1 'val22'
2 'val23'
Another function requires an array of hashes containing arrays:
<code>0 HASH(0x1f6df98)
'KEYNAME1' => ARRAY(0x1f776b0)
0 'val11'
1 'val12'
2 'val13'
1 HASH(0x1f6dfe0)
'KEYNAME2' => ARRAY(0x1f6df80)
0 'val21'
1 'val22'
2 'val23'
</code>
<code>0 HASH(0x1f6df98)
'KEYNAME1' => ARRAY(0x1f776b0)
0 'val11'
1 'val12'
2 'val13'
1 HASH(0x1f6dfe0)
'KEYNAME2' => ARRAY(0x1f6df80)
0 'val21'
1 'val22'
2 'val23'
</code>
0 HASH(0x1f6df98)
'KEYNAME1' => ARRAY(0x1f776b0)
0 'val11'
1 'val12'
2 'val13'
1 HASH(0x1f6dfe0)
'KEYNAME2' => ARRAY(0x1f6df80)
0 'val21'
1 'val22'
2 'val23'
This code converts the first to the second, but is there an easier way?
This segment of code is redundant because @{$hash{$feld}}
already contains exactly what you produce in @array
.
<code>my @array;
foreach my $wert (@ {$hash{$feld}}) {
print "wert $wert";
push @array, $wert;
}
</code>
<code>my @array;
foreach my $wert (@ {$hash{$feld}}) {
print "wert $wert";
push @array, $wert;
}
</code>
my @array;
foreach my $wert (@ {$hash{$feld}}) {
print "wert $wert";
push @array, $wert;
}
Here is a simpler solution.
<code>use Data::Dumper;
my %hash = (
KEYNAME1 => [qw( val11 val12 val12 )],
KEYNAME2 => [qw( val21 val22 val23 )],
);
print Dumper %hash;
my @array;
while ( my ($key, $val) = each %hash ) {
push @array, {$key => $val};
}
print Dumper @array;
</code>
<code>use Data::Dumper;
my %hash = (
KEYNAME1 => [qw( val11 val12 val12 )],
KEYNAME2 => [qw( val21 val22 val23 )],
);
print Dumper %hash;
my @array;
while ( my ($key, $val) = each %hash ) {
push @array, {$key => $val};
}
print Dumper @array;
</code>
use Data::Dumper;
my %hash = (
KEYNAME1 => [qw( val11 val12 val12 )],
KEYNAME2 => [qw( val21 val22 val23 )],
);
print Dumper %hash;
my @array;
while ( my ($key, $val) = each %hash ) {
push @array, {$key => $val};
}
print Dumper @array;
A map could be used instead of the while loop, but I think the loop is easier to read.
<code>my @array = map { {$_ => $hash{$_}} } keys %hash;
</code>
<code>my @array = map { {$_ => $hash{$_}} } keys %hash;
</code>
my @array = map { {$_ => $hash{$_}} } keys %hash;