Perl定制排序

Boy*_*ing 2 sorting perl

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

这是我的代码:

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
Run Code Online (Sandbox Code Playgroud)

我希望"节点"开始,但它不起作用.

结果:

abc
def
ggg
node
mmm
xxx
yyy
Run Code Online (Sandbox Code Playgroud)

预期结果:

node
abc
def
ggg
mmm
xxx
yyy
Run Code Online (Sandbox Code Playgroud)

mni*_*lle 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; 
Run Code Online (Sandbox Code Playgroud)

或者:

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