【问题标题】:Perl customized sortPerl 自定义排序
【发布时间】:2016-01-14 22:40:53
【问题描述】:

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

这是我的代码:

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

【问题讨论】:

    标签: perl sorting


    【解决方案1】:

    $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;
    }
    

    【讨论】:

    • 您错过了$a$b 都是node 的情况。固定。
    【解决方案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;
    

    【讨论】:

    • 感谢您的回答!!但我更喜欢@mnile,因为它可以很容易地移植到其他语言
    猜你喜欢
    • 2016-05-24
    • 2011-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 2014-09-10
    • 2014-07-18
    • 2011-12-16
    相关资源
    最近更新 更多