Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

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
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;

    Dave

Re: Map list of hashrefs
by AnomalousMonk (Abbot) 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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (8)
As of 2015-07-06 09:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (71 votes), past polls