Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked

Map list of hashrefs

by Anonymous Monk
on Nov 22, 2011 at 12:41 UTC ( #939446=perlquestion: print w/ replies, xml ) Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

What is the preferred way of extending/generalising this:

($hr1->{k}, $hr2->{k}, $hr3->{k}) = qw(val1 val2 val3)

I tried map but it doesn't seem to offer a solution.

Comment on Map list of hashrefs
Download Code
Replies are listed 'Best First'.
Re: Map list of hashrefs
by raybies (Chaplain) on Nov 22, 2011 at 13:05 UTC
    If you don't mind an array of hash rather than three seperate hashes with independent names, I'd do this:
    my @array = map { { k => $_ } } qw (val1 val2 val3);

    (then accessing val1 and val2 would be... etc...)

     print "$array[0]->{k} $array[1]->{k}";

Re: Map list of hashrefs
by davido (Archbishop) on Nov 22, 2011 at 13:06 UTC

    The first generalization is to use an array instead of variable names with numbers in them. Then you could do this:

    # Preserves any pre-existing anonymous hashref. @hr = map{ $hr[$_]->{k} = $val[$_] } 0 .. $#hr;

    Bah! here instead. ;)

    # Preserves any pre-existing anonymous hashref. $hr[$_]->{k} = $val[$_] for 0 .. $hr;


Re: Map list of hashrefs
by AnomalousMonk (Canon) on Nov 22, 2011 at 19:12 UTC

    Assuming you already have a bunch of hashrefs you need to corral, I would consider something like this:

    >perl -wMstrict -le "my @vals = qw(val1 val2 val3); my ($hr1, $hr2, $hr3) = ({a => 1}, {b => 2}, {c => 3}); my @h_refs = ($hr1, $hr2, $hr3); ;; die 'arrays not same size' if @h_refs != @vals; ;; $h_refs[$_]->{k} = $vals[$_] for 0 .. $#vals; ;; use Data::Dumper; print Dumper $hr1, $hr2, $hr3; " $VAR1 = { 'k' => 'val1', 'a' => 1 }; $VAR2 = { 'k' => 'val2', 'b' => 2 }; $VAR3 = { 'c' => 3, 'k' => 'val3' };

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (4)
As of 2016-02-13 09:43 GMT
Find Nodes?
    Voting Booth?

    How many photographs, souvenirs, artworks, trophies or other decorative objects are displayed in your home?

    Results (423 votes), past polls