Trying for the generic mixed case nightmare, in "obvious" mode:
#!/your/perl/here # demonstrate sorting numerically within a string # # for example, abc2xyz sorts before abc14xyz # use strict; use warnings; my @list = map { $_ . "\n" } qw( a1 a2 a10 a1a a2a a10a a01a a10b a1b2 +c a1b10c aa1 ); print sort mixed_sort @list; { # closure for caching, etc. my %seen; sub mixed_sort { return $seen{$a,$b} if exists( $seen{$a,$b} ); $seen{$a,$b} = 0; my $re_num = qr/\d+/; my $re_both = qr/^(\d+|\D+)+$/; # split into alpha and numeric fields my @x = $a =~ /$re_both/go; my @y = $b =~ /$re_both/go; my $longest = @x > @y ? @x-1 : @y-1; foreach my $i ( 0..$longest ) { if ( defined( $x[$i] ) and defined( $y[$i] ) ) { if ( ( $x[$i] =~ /^$re_num$/o ) and ( $y[$i] =~ /^$re_num$/o ) ) { $seen{$a,$b} = $x[$i] <=> $y[$i]; # both are numbe +rs } else { $seen{$a,$b} = $x[$i] cmp $y[$i]; } } elsif ( defined( $x[$i] ) ) { $seen{$a,$b} = +1; } elsif ( defined( $y[$i] ) ) { $seen{$a,$b} = -1; } # else they're both undef, and nothing changes yet return $seen{$a,$b} if $seen{$a,$b}; } return $seen{$a,$b} = $a cmp $b; # if all else fails } # end of sub mix_sort } # end of closure for sub mixed_sort __END__
Perhaps someone can add to it for generic distinctions (numbers are not just \d+), more than 2 categories, etc.

-QM
--
Quantum Mechanics: The dreams stuff is made of


In reply to Re: perl sorting by QM
in thread perl sorting by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.