Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

How to print key and value of hash in a list

by Diane4Luo
on May 22, 2011 at 21:27 UTC ( #906204=perlquestion: print w/ replies, xml ) Need Help??
Diane4Luo has asked for the wisdom of the Perl Monks concerning the following question:

How to print only value of hash in a list? Thanks,

Comment on How to print key and value of hash in a list
Re: How to print key and value of hash in a list
by spazm (Monk) on May 22, 2011 at 22:07 UTC
    values will return an array of values from a hash. The array will be in hash-sorted order.
    Similarly keys will return an array of keys from a hash. The order of the two arrays will match.
    my %hash = ( a=>1, b=>2, c=>3); my @v = values %hash; # e.g. ( 2, 3, 1 ) my @k = keys %hash; # e.g. ('b', 'c', 'a')
Re: How to print key and value of hash in a list
by kejohm (Hermit) on May 22, 2011 at 22:34 UTC

    You could also use the each function, which returns the next key and value pair of the hash, eg.

    my %hash = ( 'apple' => 'red', 'banana' => 'yellow', ); while( my( $key, $value ) = each %hash ){ print "$key: $value\n"; }

    See each for more info.

Re: How to print key and value of hash in a list
by nvivek (Vicar) on May 23, 2011 at 04:43 UTC
    You can also print the keys and values of a hash in the following way.
    my %hash = ( '1' => 'One', '2' => 'Two', '3' => 'Three', + ); print "Key: $_ and Value: $hash{$_}\n" foreach (keys%hash);
Re: How to print key and value of hash in a list
by johngg (Abbot) on May 23, 2011 at 08:58 UTC

    Some examples using the "babycart" (@{ [ ... ] }) operator to interpolate a bit of code into a double-quoted string.

    knoppix@Microknoppix:~$ perl -E ' > %hash = ( a => 1, b => 2, c => 3 ); > say qq{@{ [ values %hash ] }}; > say qq{@{ [ sort { $b <=> $a } values %hash ] }}; > say qq{@{ [ map $hash{ $_ }, sort keys %hash ] }};' 3 1 2 3 2 1 1 2 3 knoppix@Microknoppix:~$

    I hope this is helpful.

    Cheers,

    JohnGG

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (10)
As of 2014-07-30 21:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (241 votes), past polls