Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

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)

update

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

Comment on selecting values from hash via list
Select or Download Code
Re: selecting values from hash via list (slice)
by toolic (Chancellor) 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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (7)
As of 2014-08-01 08:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (257 votes), past polls