http://www.perlmonks.org?node_id=355447

neniro has asked for the wisdom of the Perl Monks concerning the following question:

I've already got a solution for this problem, but I'm still thinking about different way to do it (using map)?
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my $box = [ { id => 'q01' }, { id => 'q02' }, { id => 'q03' }, ]; my @results = qw ( foo bar buz ); my $i = 0; for (@$box) { $_->{value} = $results[$i++]; } print Dumper($box);

Replies are listed 'Best First'.
Re: Merging an array into an AoH
by BrowserUk (Patriarch) on May 21, 2004 at 20:09 UTC

    If you don't mind throwing away @results, you could do

    $_->{id} = shift @results for @box;

    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "Think for yourself!" - Abigail

      Except that should be:

      $_->{value} = shift @results for @box;

      He's assigning the data from @results to the value key. id is already in use.

      (Still, the best solution of the lot :-).

      --rjray

Re: Merging an array into an AoH
by diotalevi (Canon) on May 21, 2004 at 19:54 UTC

    Your index and increment ought not to be separate from your loop. That's gross.

    for my $ix ( 0 .. $#$box ) { $box->[ $ix ]{ 'value' } = $results[ $ix ]; }
Re: Merging an array into an AoH
by geekgrrl (Pilgrim) on May 21, 2004 at 20:39 UTC
    Are those ids unique? They look like it. If so, I think a hash of hashes would be a better data structure for your problem.
    my $box = { q01 => {}, ... q03 => {} }; #this should keep them in the right order my @sorted_keys = sort {lc $a cmp lc $b} keys %{$box} ; for my $id (@sorted_keys) { $box->{$id}{value} = shift @results; }
      I prefer an AoH, cause I can use them directly within HTML::Template. The solutions above ar quite cool, especially BrowserUKs.
      Thanks a lot!