nysus has asked for the wisdom of the Perl Monks concerning the following question:

I have a hash where each key is an event on a calendar and each value is the date of that event. What I want to do is place the events in chronological order. In other words, I want to sort the hash's keys using the hash's values. Here's the syntax of the hash I'm using:
$orderentry{$calentry} = $date;
It's not possible to look up the events with the date because a date can have more than one event. What's the best way to handle this? By writing a complicated sort subroutine? Would Perl references (which I still need to learn) make this easier to do?

Replies are listed 'Best First'.
Re: Sorting hashes with values
by jeroenes (Priest) on Apr 09, 2001 at 20:13 UTC
    I wouldn't be suprised if this is a FAQ. You just have to supply the right sub to sort:
    @sorted_events = sort { $dates{$a} <=> $dates{$b} } keys %dates;
    Hope this helps,

    Jeroen
    "We are not alone"(FZ)
    Update: Added that s. Thx Beatnik and ar0n

      Got it. Forgot about those FAQs. Thanks.
Re: Sorting hashes with values
by physi (Friar) on Apr 09, 2001 at 20:26 UTC
    Hi, well you should try to make the date the key, and put your events into a array of your hash key:
    my %date; $date{1.1.2001}="Happy new year"; push @{$date{1.1.2001}, "Don't drink and drive";
    you can now access the events by:
    for $event (@{$date{1.1.2001}) { print "$event on 1.1.2001\n" }
    This is maybe easier than do it the other way around.
    Every value of this %year-hash is an array itself.

    ----------------------------------- --the good, the bad and the physi-- -----------------------------------