Search code examples
perlsortinghash-reference

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


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?


Solution

  • 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.