in reply to Shrink this sort subroutine

Just as a remark, you might want to use UNIX time_t format instead of this ASCII-ified version YYYY-MM-DD etc. If you use time_t, you can convert between time zones, and allow for "Daylight Savings Time" settings. If everything is set to GMT, of course, which it should be by default. time_t is what the time function spits out by default.

Then, provided you are doing numeric comparisons, you can sort them with ease. This is super-ultra important, because time_t is rolling over to 10 digits and you don't want to fall victim to The Y2.001775K Bug.

Until September 9, 2001, you can get away with sorting using the default string method. However, any dates after that point will sort back into 1973 territory, which is the bad kind of retro.

So, you can sort them like so:
sub bycreatetime { return $nodes{$a}{createtime} - $nodes{$b}{createtime}; } foreach $node (sort { bycreatetime } keys %nodes) { # ... }
As an added bonus, I see that you're comparing your '$sort_field' variable. Consider the following improvement:
my (%sort_method) = ( createtime => \&bycreatetime, createuser => \&bycreateuser, # For example ); foreach $node (sort $sort_method{$sort_field} keys %nodes) { # ... }
Or, for continued amusement:
sub NumericalSort { my ($field) = @_; return sub { return $nodes{$a}{$field} - $nodes{$a}{$field}; }; } my (%sort_method) = ( createtime => NumericalSort('createtime'), ); foreach $node (sort $sort_method($sort_field) keys %nodes) { # ... }

Replies are listed 'Best First'.
Re: Re: Shrink this sort subroutine
by $code or die (Deacon) on Apr 25, 2001 at 01:19 UTC
    ++! Thanks for pointing that out!

    Just in case some other people (like I did) gasp and think that everything time is going to roll over to 000000000 on Sept 9th, it won't it will become 1000000000, its just sorting dates without taking this into account will end up with this phenomenon:
    042312313 (Apr 15 1970) 1028542120 (Aug 5 2002) 171024424 (Jun 3 1975) 514542121 (Apr 22 1986) 941244212 (Oct 30 1999) 974124124 (Nov 13 2000) 987451241 (Apr 16 2001) 988145259 (Apr 24 2001)
    You can probably see the error. So be careful. Thanks tadman

    Update: Hmm, I should have followed your link, before posting this. I blame the caffeine!

    $ perldoc perldoc