Perl 排序数组:保留以 # 开头的项目



有没有办法修改任何以#开头的字符串被忽略的排序,即保留其索引?

例如:

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

@sorted_stooges应该给出:

Curly
Iggy
Larry
Moe

现在,如果我将#添加到卷曲

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

我希望@sorted_stooges成为:

Iggy
#Curly
Larry
Moe

就地解决方案:

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];

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

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

(不幸的是,@$slice = sort @$slice;不起作用 - 它替换了@$slice的元素而不是分配给它们 - 但找到了合适的替代方案。

提取要排序的元素,然后使用排序的元素更新原始数组:

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提出了这种方法的一种变体,其中提取要排序的元素的索引,而不是元素本身。该解决方案允许数组元素与列表切片优雅地交换。

最新更新