Sorting and undefined values

Andy Armstrong andy at hexten.net
Tue Dec 12 17:20:59 GMT 2006


On 12 Dec 2006, at 17:00, Earle Martin wrote:
> I have this code:
>
> my @sorted = sort {
>  $foo->{$a}->{'x'} cmp $foo->{$b}->{'x'} ||
>  $foo->{$b}->{'y'} cmp $foo->{$b}->{'y'}
> } keys %$foo;
>
> This only produces the keys of items where 'x' is defined. What do I
> need to do to sort first on 'x' if it's defined, and then on 'y', or
> just 'y' if 'x' is undefined?

What has to happen in the case where x is defined for one side of the  
comparison but not the other? Do you want to compare x only if x is  
defined for both sides? And by defined do you actually mean exists?

Perhaps:

(exists $foo->{$a}->{'x'} &&
  exists $foo->{$b}->{'x'} &&
  $foo->{$a}->{'x'} cmp $foo->{$b}->{'x'}) || $foo->{$a}->{'y'} cmp  
$foo->{$b}->{'y'}

?

-- 
Andy Armstrong, hexten.net



More information about the london.pm mailing list