Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

How to print key and value of hash in a list

by Diane4Luo (Initiate)
on May 22, 2011 at 21:27 UTC ( [id://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

Replies are listed 'Best First'.
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 (Canon) 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
Domain Nodelet?
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?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (2)
As of 2024-04-24 13:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found