How to display the special value always at top while sorting?

88 Views Asked by At

I used the below code to sort values and display it as a dropdown in a Perl form page And I need to display a certain value always at the top of the sorted list, how to do that?

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

I tried this too,not working with me for some reason

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

Any help?

3

There are 3 best solutions below

2
AnFi On BEST ANSWER

You can sort $special value like the lowest using (($b eq $special) - ($a eq $special)) as the first link in "sORt chain":

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)) returns:
0 when $a and $b are special [$a is equal $b]
-1 when $a is special and $b is not [$a less than $b]
+1 when $b is special and $a is not [$a greater than $b]
0 when both $a and $b are not special [$a is equal $b]

When it produces 0 next links in the sORt chain are queried.

3
V-Mark On

slice the 1st element before sort than put it back before display, like

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

# sort it or do what you want

unshift(@foo,$bar);

print @foo, "\n";
0
Borodin On

Assuming your hash contains only non-negative keys, you can sort the header values as if they were -∞ which will sort before anything else, but will be equal to itself

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