Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: sort after first char of hash key

by Cristoforo (Deacon)
on Jun 03, 2011 at 00:38 UTC ( #907901=note: print w/ replies, xml ) Need Help??


in reply to sort after first char of hash key

Here is the Guttman-Rosler Transform.

#!/usr/bin/perl use strict; use warnings; use 5.012; use List::Util qw/ shuffle /; srand(1); # to get same random 'shuffle' from run to run my @list = shuffle (qw/ Y2 A15 YABBA287 DABBA345 DOO777/, map {"E$_"} +(1..20)); say "UNSORTED"; say "@list"; my @sorted = map { my $strlength = unpack("C", substr($_, -1)); substr $_, -1 * (1 + $strlength), -1; } sort map { pack "a*Na*C", /(\D+)(\d+)/, $_, length} @list; say "SORTED"; say "@sorted";

The advantage of this sort is that it uses a simple alphabetical sort. Its is usually the fastest performing sort. The configuration here will sort any 'alpha'+'number' string, not just a single leading letter plus a number.

Update: The setup here is limited to strings of length <= 255. If the strings to be sorted are longer than that, you would have to make some changes. Also, to make the sort case insensitive, which is usually the desired outcome, the first map could be restated as:

map { pack "a*Na*C", (map {lc} /(\D+)(\d+)/), $_, length} @list;

by adding the lc operator.


Comment on Re: sort after first char of hash key
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://907901]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (2)
As of 2014-10-01 00:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (386 votes), past polls