Skip to content

Instantly share code, notes, and snippets.

@chiral
Created May 29, 2013 12:32
Show Gist options
  • Select an option

  • Save chiral/5669938 to your computer and use it in GitHub Desktop.

Select an option

Save chiral/5669938 to your computer and use it in GitHub Desktop.
natural sort in perl
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