http://www.perlmonks.org?node_id=598649


in reply to Re^4: RFC:A brief tutorial on Perl's native sorting facilities.
in thread RFC:A brief tutorial on Perl's native sorting facilities.

Yes, you would ask the object to give you a key (or generate the key based on some of the objects' properties) and use that to populate the @keys array in my example or the keys in the two item arrays of ST. The thing is that the GT prepends the key (either using . or pack()) to the stringified values of the items, sorts the results and then strips the keys. It's not a matter of outperforming, it's a matter of either returning useless stuff or having to bend backwards and ending up with copies.

Let's assume you have an array containing hashes like this and want to sort them by, let's say, the birth_date:

@list = ( {fname => 'Jan', lname => 'Krynicky', birth_date => 'Sep 3 1975', #... }, {fname => 'Pavel', lname => 'Krynicky', birth_date => 'Dec 25 1969', #... }, {fname => 'Martin', lname => 'Krynicky', birth_date => 'Aug 24 1973', #... }, );
Sort this using GRT!

use Date::Calc qw(Decode_Date_US); use Data::Dumper; sub convertdate { return sprintf '%04d%02d%02d', Decode_Date_US($string) } # ST @sorted = map{ $_->[1] } sort{ $a->[0] <=> $b->[0] } map{ [ convertdate($_->{birth_date}), $_ ] } @list; print Dumper(\@sorted); # @keys array { my @keys = map convertdate($_->{birth_date}), @list; @sorted = @list[ sort {$keys[$a] cmp $keys[$b]} (0..$#list) ]; } print Dumper(\@sorted); # GRT @sorted = map{ ## Chop off the bit we added. substr( $_, 8 ) } sort map{ ## Note: No comparison block callback. ## Extract the field as before, but concatenate it with the origin +al element ## instead of building an anonymous array containing both elements +. convertdate($_->{birth_date}) . $_ } @list; print Dumper(\@sorted);
Whoops?!?
$VAR1 = [ 'HASH(0x18db494)', 'HASH(0x224e9c)', 'HASH(0x224fa4)' ];
?!?