Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

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

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 meditating upon the Monastery: (8)
As of 2016-08-25 23:32 GMT
Find Nodes?
    Voting Booth?
    The best thing I ever won in a lottery was:

    Results (363 votes). Check out past polls.