use strict;
my $DATA;
{
local $/ = undef;
my $DATA_text = ;
eval "$DATA_text";
die $@ if $@;
}
print "# incorrect reverse sort using reverse function\n";
foreach my $date (reverse keys %{$DATA}) {
print "$date\n";
}
print "\n";
print "# correct reverse sort\n";
foreach my $date (sort {$b cmp $a} keys %{$DATA}) {
print "$date\n";
}
__DATA__
$DATA = {
'2009/07/19' => {
files => 1,
},
'2009/07/12' => {
files => 1,
},
'2009/07/05' => {
files => 1,
},
'2009/06/28' => {
files => 1,
},
'2009/06/21' => {
files => 1,
},
};
It prints:
>perl reverse_problem.pl
# incorrect reverse sort using reverse function
2009/07/12
2009/07/05
2009/07/19
2009/06/28
2009/06/21
# correct reverse sort
2009/07/19
2009/07/12
2009/07/05
2009/06/28
2009/06/21
>perl -v
This is perl, v5.8.8 built for MSWin32-x86-multi-thread
(with 18 registered patches, see perl -V for more detail)
Copyright 1987-2007, Larry Wall
Binary build 822 [280952] provided by ActiveState http://www.ActiveState.com
Built Jul 31 2007 19:34:48
Perl may be copied only under the terms of either the Artistic License or the
GNU General Public License, which may be found in the Perl 5 source kit.
Complete documentation for Perl, including FAQ lists, should be found on
this system using "man perl" or "perldoc perl". If you have access to the
Internet, point your browser at http://www.perl.org/, the Perl Home Page.
--Apparently I can reproduced this using ActiveState v5.10.0 build 1001 [283495]
2 comments:
You're missing an important fact there, the "keys" function does not return the hash keys in a predictable order. So "reverse keys" could output an equally random ordered result.
See perldoc -f keys:
The keys are returned in an apparently random order.
Jess
Yes, my presumption was: reverse will sort the array in descending manner.
I keep reminding myself nowadays that reverse doesn't sort.
Post a Comment