0

A function produces this hash of arrays:

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

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?

closed as off topic by World Engineer, Walter, Matthieu, user8, Ryathal Sep 14 '12 at 19:54

Questions on Software Engineering Stack Exchange are expected to relate to software engineering within the scope defined by the community. Consider editing the question or leaving comments for improvement if you believe the question can be reworded to fit within the scope. Read more about reopening questions here. If this question can be reworded to fit the rules in the help center, please edit the question.

1

This segment of code is redundant because @{$hash{$feld}} already contains exactly what you produce in @array.

my @array;
foreach my $wert (@ {$hash{$feld}}) {
    print "wert $wert";
    push @array, $wert;
}

Here is a simpler solution.

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.

my @array = map { {$_ => $hash{$_}} } keys %hash;

Not the answer you're looking for? Browse other questions tagged or ask your own question.