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

Re: [MacPerl] Accessing Hash with Value




>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?

Did you assign something to $key?

>From the perl FAQ:
http://www.perl.org/CPAN/doc/manual/html/pod/perlfaq4/How_do_I_sort_a_hash_optio
naly.html

---
How do I sort a hash (optionally by value instead of key)?

Internally, hashes are stored in a way that prevents you from imposing an
order on key-value pairs. Instead, you have to sort a list of the
keys or values:

    @keys = sort keys %hash;    # sorted by key
    @keys = sort {
                    $hash{$a} cmp $hash{$b}
            } keys %hash;       # and by value

Here we'll do a reverse numeric sort by value, and if two keys are
identical, sort by length of key, and if that fails, by straight ASCII
comparison of the keys (well, possibly modified by your locale -- see the
perllocale manpage).

    @keys = sort {
                $hash{$b} <=> $hash{$a}
                          ||
                length($b) <=> length($a)
                          ||
                      $a cmp $b
    } keys %hash;

---

Cheers,
Paul



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