icon Top 9 categories map      RocketAware > Perl >

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

Tips: Browse or Search all pages for efficient awareness of Perl functions, operators, and FAQs.



Home

Search Perl pages


Subjects

By activity
Professions, Sciences, Humanities, Business, ...

User Interface
Text-based, GUI, Audio, Video, Keyboards, Mouse, Images,...

Text Strings
Conversions, tests, processing, manipulation,...

Math
Integer, Floating point, Matrix, Statistics, Boolean, ...

Processing
Algorithms, Memory, Process control, Debugging, ...

Stored Data
Data storage, Integrity, Encryption, Compression, ...

Communications
Networks, protocols, Interprocess, Remote, Client Server, ...

Hard World
Timing, Calendar and Clock, Audio, Video, Printer, Controls...

File System
Management, Filtering, File & Directory access, Viewers, ...

    

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;


Source: Perl FAQ: Data Manipulation
Copyright: Copyright (c) 1997 Tom Christiansen and Nathan Torkington.
Next: How can I always keep my hash sorted?

Previous: How can I know how many entries are in a hash?



(Corrections, notes, and links courtesy of RocketAware.com)


[Overview Topics]

Up to: Sorting Algorithms
Up to: Data structures (In memory)




Rapid-Links: Search | About | Comments | Submit Path: RocketAware > Perl > perlfaq4/How_do_I_sort_a_hash_optionally.htm
RocketAware.com is a service of Mib Software
Copyright 2000, Forrest J. Cavalier III. All Rights Reserved.
We welcome submissions and comments