Perl定制排序

时间:2016-01-14 06:58:13

标签: perl sorting

我想对数组进行排序,并将特定元素放在开头。

这是我的代码:

sub MySort {
    my $P = 'node';
    if ($a eq $P) {
        return -1;
    }

    return -1 if $a lt $b;
    return 0  if $a eq $b;
    return 1  if $a gt $b;
}

my @x = qw (abc def xxx yyy ggg mmm node);
print join "\n",sort MySort @x

我希望"节点"到了开头,但它没有用。

结果:

abc
def
ggg
node
mmm
xxx
yyy

预期结果:

node
abc
def
ggg
mmm
xxx
yyy

2 个答案:

答案 0 :(得分:5)

$bnode时,您错过了案例。

sub MySort {     
    my $P = 'node';
    return  0 if $a eq $P && $b eq $P;
    return -1 if $a eq $P;
    return +1 if $b eq $P;
    return $a cmp $b;
}

my @x = qw (abc def xxx yyy ggg mmm node); 
my @a = sort MySort @x; 

可替换地:

sub MySort {     
    my $P = 'node';
    return ($a eq $P ? 0 : 1) <=> ($b eq $P ? 0 : 1)
        || $a cmp $b;
}

答案 1 :(得分:2)

如果您不想手动编写此类内容,可以使用Sort::ByExample,它专门用于将预定义值列表排序到列表前面(如果出现),按照你喜欢的方式排列剩下的。以你的例子:

use Sort::ByExample;
my $sorter = Sort::ByExample->sorter(
    ['node'],
    sub { $_[0] cmp $_[1] }
);
my @x = qw (abc def xxx yyy ggg mmm node);
print join "\n", $sorter->(@x);

或者,如果你真的想要一个sub,你可以使用内置sort

use Sort::ByExample;
my $mysort = Sort::ByExample->cmp(
    ['node'],
    sub { $_[0] cmp $_[1] }
);
my @x = qw (abc def xxx yyy ggg mmm node);
print join "\n", sort $mysort @x;