Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses

Re: How do I do a natural sort on an array?

by Dominus (Parson)
on Mar 30, 2001 at 19:19 UTC ( #68394=note: print w/replies, xml ) Need Help??

in reply to How do I do a natural sort on an array?

I'm not exactly sure what you want (it would have helped if you had provided an example) but here's what I use:
sub byfile { my @a = split /(\d+)/, $a; my @b = split /(\d+)/, $b; my $M = @a > @b ? @a : @b; my $res = 0; for (my $i = 0; $i < $M; $i++) { return -1 if ! defined $a[$i]; return 1 if ! defined $b[$i]; if ($a[$i] =~ /\d/) { $res = $a[$i] <=> $b[$i]; } else { $res = $a[$i] cmp $b[$i]; } last if $res; } $res; }
This may be more complicated than you need. Given the following:
53 7 119 53red red5 red6 red7 red67 red6.jpg red12.jpg green4.jpg blue2.jpg blue1000.jpg blue2.jpg58
it produces the following output:
7 53 53red 119 blue2.jpg blue2.jpg58 blue1000.jpg green4.jpg red5 red6 red6.jpg red7 red12.jpg red67
Lucs St. Louis also suggests:
while (defined (my $A = shift @a) and defined (my $B = shift @b)) { $res = ($A =~ /\d/) ? $A <=> $B : $A cmp $B; return $res if $res; } return defined $A ? -1 : 1;
Hope this helps.

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (2)
As of 2022-05-29 07:58 GMT
Find Nodes?
    Voting Booth?
    Do you prefer to work remotely?

    Results (101 votes). Check out past polls.