Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Merging an array into an AoH

by neniro (Priest)
on May 21, 2004 at 19:46 UTC ( #355447=perlquestion: print w/replies, xml ) Need Help??

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!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://355447]
Approved by kvale
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (1)
As of 2022-06-26 14:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My most frequent journeys are powered by:









    Results (85 votes). Check out past polls.

    Notices?