http://qs1969.pair.com?node_id=906204

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