in reply to sorting a split hash

This is a perfect candidate for an ST sort!

#!/usr/bin/perl use strict; use warnings; use HTTP::Date; # needed for str2time my %hash; while(<DATA>) { my ($key,$value) = /(\S+) => (.*)$/; $hash{$key} = $value; } my @sorted_keys = map $_->[0] => sort { $a->[1] cmp $b->[1] } map [ $_, # This is where we extract the value1 # -- [0] in the array returned from # the split --, and convert it to # a time value to be used in the sort. str2time((split(/\|/,$hash{$_}))[0]) ] => keys %hash; for my $key (@sorted_keys) { print "$key => $hash{$key}\n"; } __DATA__ index.html => Mon Oct 11 00:08:11 2004|12963 screenshot.jpg => Sun Oct 10 13:18:30 2004|234997 legal.html => Mon Oct 11 12:57:03 2004|13448 stylesheet.css => Mon Oct 11 13:57:28 2004|697 about.html => Mon Oct 11 00:08:08 2004|13225 archive.html => Mon Oct 11 00:08:09 2004|12872 postinfo.html => Fri Oct 1 23:49:15 2004|2457 contact.shtml => Mon Oct 11 00:09:48 2004|11366 services.html => Mon Oct 11 00:08:17 2004|14256 metatags.pl => Mon Oct 11 14:05:44 2004|28668 tools.html => Mon Oct 11 15:35:47 2004|14632 robots.txt => Sat Oct 9 03:35:15 2004|73 _vti_inf.html => Fri Oct 1 23:49:15 2004|1754 report.shtml => Mon Oct 11 00:07:03 2004|11686

Hope this helped,
-v
"Perl. There is no substitute."

Replies are listed 'Best First'.
Re^2: sorting a split hash
by shenme (Priest) on Oct 12, 2004 at 04:39 UTC
    As long as we have the nit combs out, and while coldfingers forgot to mention it, you might want to add a specific ordering for the keys if their values happen to have the same timestamp
    sort { $b->[1] <=> $a->[1] || $a->[0] cmp $b->[0] }
    coldfingers will have to decide whether they want to swap the $a and $b, now that sulfericacid has mentioned it matters. Oh, and I really think that should be a <=> first as the value returned from str2time (thank you for pointing it out!) seems to be a number. Don't want any problems with dates before September 2001.
Re^2: sorting a split hash
by sulfericacid (Deacon) on Oct 12, 2004 at 04:10 UTC
    Wouldn't you have to reverse sort the array? I tried this and it actually prints in reverse chronological order (oldest on top, newest on bottom)


    "Age is nothing more than an inaccurate number bestowed upon us at birth as just another means for others to judge and classify us"

    sulfericacid