perl排序数组:保留一个以#就地开头的项目

时间:2018-01-22 15:13:54

标签: perl sorting

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

例如:

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

my @sorted_stooges = sort @stooges;

@sorted_stooges应该给出:

Curly
Iggy
Larry
Moe

现在,如果我将#添加到Curly

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

my @sorted_stooges = sort @stooges;

我希望@sorted_stooges成为:

Iggy
#Curly
Larry
Moe

2 个答案:

答案 0 :(得分:10)

就地解决方案:

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的元素而非分配给它们 - 但找到了合适的替代方案。)

答案 1 :(得分:5)

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

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;

在他们的回答中,@ higgami建议使用这种方法的变体,其中提取要排序的元素的索引,而不是元素本身。该解决方案允许使用列表切片优雅地交换数组元素。