Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

selecting values from hash via list

by leocharre (Priest)
on Nov 06, 2009 at 21:01 UTC ( #805582=perlquestion: print w/ replies, xml ) Need Help??
leocharre has asked for the wisdom of the Perl Monks concerning the following question:

I have a hash or hashref. Let's make it easy, a hash.
my %h = ( name => 'dumdum', age => 14, zone => 'a4', pocket => 'empty', );
I'm going to print some of this data with printf..
printf "%-20s %5d %s\n", $h{name}, $h{age}, $h{zone};

What's another way to specify those three values? Specifically, as you would as list args.. I know this has to be out there.

I like this trick to init hash keys (learned it here)..

my %a; my @a = qw/name age zone pocket/; @a{@a}=(); # looks weird, eh? ;-) # now 'exists $a{name}' is true!
Maybe there's some way to ...err... uhhhm ...
printf "%-20s %5d %s\n", @h{qw/name age zone/};

(sorry about the title, dunno how else the heck to word this)


Silly me, that second example, that was the solution, thanks toolic

Comment on selecting values from hash via list
Select or Download Code
Replies are listed 'Best First'.
Re: selecting values from hash via list (slice)
by toolic (Bishop) on Nov 06, 2009 at 21:14 UTC
    I'm confused. Your 2 printf statements print the same thing for me. Isn't that what you want -- to use a hash slice to save typing? See Slices.
    printf "%-20s %5d %s\n", $h{name}, $h{age}, $h{zone}; printf "%-20s %5d %s\n", @h{qw/name age zone/};
      Oh.. dear... it works.. I thought I was making up code!

      I thought this was nonsense! : printf "%-20s %5d %s\n", @h{qw/name age zone/};

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (11)
As of 2015-10-06 19:45 GMT
Find Nodes?
    Voting Booth?

    Does Humor Belong in Programming?

    Results (160 votes), past polls