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

my $hash = { env4 => 20140830 env1 => 20140829 env2 => 20140828 env3 => 20140828 };
I have a whole bunch of environments env1, env2, etc each with a corresponding date. I want to simply loop through the key value pairs in order of descending date (i.e larger dates first). If the environments have the same date, order does not matter. Basically, I want to do a reverse sort by value (not key) of the pairs that come out of perl each... but how??? I've also seen on the Internet that "each" should be avoided... So i want to end up with the following output:
env4, 20140830 env1, 20140829 env2, 20140828 env3, 20140828
thanks! Michael

Replies are listed 'Best First'.
Re: struggling with what should be a very simple perl task
by davido (Cardinal) on Aug 22, 2014 at 16:44 UTC
    my $href = { env4 => 20140830, env1 => 20140829, env2 => 20140828, env3 => 20140828, }; print "$_, $href->{$_}\n" for sort { $href->{$b} <=> $href->{$a} } key +s %$href;

    If instead of a hash ref you have plain hash, it would change:

    my %hash = ( ..... ); print "$_, $hash{$_}\n" for sort { $hash{$b} <=> $hash{$a} } keys %has +h;

    But the hash construction you demonstrated in your example (despite missing commas) appeared to be the construction of a reference to an anonymous hash.


    Dave

      that was way too easy! thank you, Dave!
Re: struggling with what should be a very simple perl task
by AnomalousMonk (Archbishop) on Aug 22, 2014 at 16:55 UTC

    See also "How do I sort an array by (anything)?" in "Data: Arrays" section of perlfaq4.