That's a fun homework. Here's a stable sort (groups maintain their positions relative to each other). That is, given the input
xxxxxC ABrrrr e_3_ee xxxxxA AArrrr e_2_ee xxxxxB ACrrrr e_1_ee
the output is
xxxxxC AArrrr e_1_ee xxxxxB ABrrrr e_2_ee xxxxxA ACrrrr e_3_ee
Another variation of a Schwartzian transform. sort doesn't sort arrays in place (doesn't sort arrays at all, only lists), so we sort each group separately and use slice assignement to restore order.
use strict; use warnings; my @array = qw( xxxxxC ABrrrr e_3_ee xxxxxA AArrrr e_2_ee xxxxxB ACrrrr e_1_ee ); my $sorted = sort_array( \@array ); print $_, "\n" for @$sorted; exit 0; use constant { KEY => 0, # sort key POS => 1, # position in array }; sub get_sort_data { my ($ary) = @_; my %result; for my $i ( 0 .. $#$ary ) { my ( $elem, $key, $name ) = $ary->[$i]; if ( $elem =~ /r/ ) { $key = $elem; $name = 'Rs'; } elsif ( $elem =~ /\Ae/ ) { $key = substr $elem, 2, 1; $name = 'Es'; } else { $key = substr $elem, -1; $name = 'Os'; # others } push @{ $result{$name} }, [ $key, $i ]; } return \%result; } sub sort_positions { sort { $a <=> $b } map $_->[POS], @_; } sub sort_array { my ($array) = @_; my $data = get_sort_data($array); my @rs = sort { $a->[KEY] cmp $b->[KEY] } @{ $data->{Rs} }; my @es = sort { $a->[KEY] cmp $b->[KEY] } @{ $data->{Es} }; my @os = sort { $b->[KEY] cmp $a->[KEY] } @{ $data->{Os} }; my @result; @result[ sort_positions(@rs), sort_positions(@es), sort_positions(@os), ] = map $array->[ $_->[POS] ], @rs, @es, @os; return \@result; }

In reply to Re: How to perform different sorts on multiple sections of items in the same array by Anonymous Monk
in thread How to perform different sorts on multiple sections of items in the same array by estreb

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.