Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic

Merging an array into an AoH

by neniro (Priest)
on May 21, 2004 at 15: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 16: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 :-).


Re: Merging an array into an AoH
by diotalevi (Canon) on May 21, 2004 at 15: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 16: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?

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

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (5)
As of 2023-12-07 17:06 GMT
Find Nodes?
    Voting Booth?
    What's your preferred 'use VERSION' for new CPAN modules in 2023?

    Results (33 votes). Check out past polls.