排序时如何在顶部显示特殊值?

时间:2017-10-19 07:06:55

标签: perl sorting hash-reference

我使用下面的代码对值进行排序并将其显示为Perl表单页面中的下拉列表我需要始终在排序列表的顶部显示某个值,该怎么做?

 values= [sort {$a<=>$b and $orig->{$a} cmp $orig->{$b}} keys  %$orig] 

我也试过这个,因为某些原因不和我合作

values= [sort {if ($a eq 'somevalue') { return 1; }
elsif ($b eq 'somevalue') { return -1; }
else { return {$a<=>$b and $orig->{$a} cmp $orig->{$b}} keys  %$orig ;} }] 

任何帮助?

3 个答案:

答案 0 :(得分:0)

在排序之前切割第一个元素,而不是在显示之前将其放回,如

my @foo = ( header, 4, 5, 6 );
$bar = shift(@foo);

# sort it or do what you want

unshift(@foo,$bar);

print @foo, "\n";

答案 1 :(得分:0)

您可以使用$special作为“s OR t链”中的第一个链接,将(($b eq $special) - ($a eq $special))值排序为最低值:

my $special = "somevalue";
sort { (($b eq $special) - ($a eq $special)) || 
       $a<=>$b || $orig->{$a} cmp $orig->{$b} } keys  %$orig;

(($b eq $special) - ($a eq $special))返回:
{$ 1}}当$ a和$ b特殊时[$ a等于$ b]
{$ 1}}当$ a是特殊的而$ b不是[$ a小于$ b]时 {$ 1}}当$ b特殊且$ a不是[$ a大于$ b]时 {$ 1}}当$ a和$ b都不特殊时[$ a等于$ b]

当它产生0时,查询s OR t链中的下一个链接。

答案 2 :(得分:0)

假设您的哈希只包含非负键,那么您 可以将标头值排序为-∞ 它将先于其他任何东西排序,但将等于 本身

sort {
    my ($aa, $bb) = map { $_ eq $special ? -Inf : $_ } $a, $b;
    $aa <=> $bb and $orig->{$aa} cmp $orig->{$bb};
} keys %$orig;