[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] Accessing Hash with Value



At 6.44 97/4/22, Chris Ouellette wrote:
>Code Snippet:
>-------------------------------------
>foreach $value (sort values %hash) {
>        print "$key has $value votes";
>}
>--------------------------------------
>$key here has no assigned value. How can I get the key to print with it's
>associated value?

You need to read up a bit on foreach, values, keys, and sort (use the Blue
Camel! :-).  And yes, this shouldn't be posted to MacPerl.  Anyway, there
are lots of ways to do it.  One thing to remember is you cannot get a key
for a specified value.  You can only get a value for a specified key.
There is no such thing as an associated key for a given value.

But the sort function is your very good friend.  Where is says
"numerically" below you can substitute the name of any subroutine that
compares the value of $a vs. $b using either 'cmp' for strings or '<=>' for
numbers.  Or you can just use the anonymous subroutine form: "sort {$a <=>
$b}".  As you can see below, you can do whatever you want to compare the
two variables, such as {$hash{$a} cmp $hash{$b}}, which is what you want.

#=========================================
#!perl
$hash{'q1'} = 2000;
$hash{'q2'} = 5000;
$hash{'q3'} = 1000;
$hash{'q4'} = 3000;
$hash{'q5'} = 4000;

foreach $key (sort numerically keys %hash) {
        print "$key has $hash{$key} votes\n";
}

sub numerically {$hash{$a} cmp $hash{$b}}
#=========================================

Or, for reverse sorting, simply use "reverse sort".

Good luck,

#================================================================
Chris Nandor                                      pudge@pobox.com
PGP Key 1024/B76E72AD                           http://pudge.net/
Keyfingerprint = 08 24 09 0B CE 73 CA 10  1F F7 7F 13 81 80 B6 B6



***** Want to unsubscribe from this list?
***** Send mail with body "unsubscribe" to mac-perl-request@iis.ee.ethz.ch