Created
May 29, 2013 12:32
-
-
Save chiral/5669938 to your computer and use it in GitHub Desktop.
natural sort in perl
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| sub mycmp { | |
| my $an = @{$a->[1]}+@{$a->[2]}; | |
| my $bn = @{$b->[1]}+@{$b->[2]}; | |
| my $n = $an<$bn ? $an : $bn; | |
| foreach my $i (0..$n-1) { | |
| my $aa = $a->[$i%2+1][$i/2]; | |
| my $bb = $b->[$i%2+1][$i/2]; | |
| my $res = $aa=~/^\d+$/ && $bb=~/^\d+$/ ? $aa <=> $bb : $aa cmp $bb; | |
| return $res if ($res!=0); | |
| } | |
| return -1 if ($an<$bn); | |
| return +1 if ($an>$bn); | |
| return 0; | |
| } | |
| @sorted=sort mycmp (map { | |
| /^\d/ | |
| ? [$_,[split /\D+/],[split /\d+/]] | |
| : [$_,[split /\d+/],[split /\D+/]] | |
| } <>); | |
| print $_->[0] for @sorted; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment