Perl sort array: leave C # element in place

Is there a way to change the sorting that any line starts with C # is ignored, i.e. retains its index?

For instance:

my @stooges = qw(
        Larry
        Curly
        Moe
        Iggy
    );

my @sorted_stooges = sort @stooges;

@sorted_stooges must indicate:

Curly
Iggy
Larry
Moe

Now, if I add # to Curly

my @stooges = qw(
            Larry
            #Curly
            Moe
            Iggy
        );

my @sorted_stooges = sort @stooges;

I would like @sorted_stooges to be:

Iggy
#Curly
Larry
Moe
+4
source share
2 answers

On-site solutions:

my @indexes_to_sort = grep { $array[$_] !~ /^#/ } 0..$#array;
my @sorted_indexes = sort { $array[$a] cmp $array[$b] } @indexes_to_sort;
@array[@indexes_to_sort] = @array[@sorted_indexes];

or

my @indexes_to_sort = grep { $array[$_] !~ /^#/ } 0..$#array;
@array[@indexes_to_sort] = sort @array[@indexes_to_sort];

or

my $slice = sub { \@_ }->( grep { !/^#/ } @array );
@$slice[0..$#$slice] = sort @$slice;

(Unfortunately, it @$slice = sort @$slice;does not work - it replaces the elements @$slice, not assigns them - but a suitable alternative is found.)

+10
source

Extract the elements to sort, then update the original array with sorted elements:

my @stooges = qw( Larry #Curly Moe Iggy );
my @sorted_items = sort grep { not /^#/ } @stooges;
my @sorted_stooges = map { /^#/ ? $_ : shift @sorted_items } @stooges;
say for @sorted_stooges;

@ikegami , , , . .

+5

Source: https://habr.com/ru/post/1692542/


All Articles