# Sorting based on existence of keys - Page 2

•  Subject
• Author
• Posted on

## Re: Sorting based on existence of keys

wrote:

I think cmp AND <=> were exactly the right tools.
This should work for you.

Thanks for posting this!
-sln

-----------------------------------------
## sort_junk.pl
## -sln
##
use strict;
use warnings;

my @ks = qw(two three one four);
my %h = ( one => 1,
three => 333 );

## Could probably take advantage of an apparent bug/feature that exists()
returns stringified '1' for true and '' for false.
## As in \$vvv = ''; print "not '\$vvv'\n" if (!\$vvv);

for (sort {
my \$Ea = exists \$h;
my \$Eb = exists \$h;
my \$comp = \$Eb cmp \$Ea;
print "a=\$a , b=\$b , Ea='\$Ea'(".length(\$Ea)."), Eb='\$Eb'(".length(\$Eb)."),
cmp=\$comp\n";
\$Ea != \$Eb ?
\$Eb cmp \$Ea :
length \$h <=> length \$h
} @ks)
{ print "\$_\n" }

for (sort {
my (\$xb, \$xa) = (exists \$h, exists \$h);
!(\$xb & \$xa) ? \$xb cmp \$xa : length \$h <=> length \$h
} @ks)
{ print "\$_\n" }

__END__

output:

a=two , b=three , Ea=''(0), Eb='1'(1), cmp=1
a=one , b=four , Ea='1'(1), Eb=''(0), cmp=-1
a=three , b=one , Ea='1'(1), Eb='1'(1), cmp=0
a=three , b=four , Ea='1'(1), Eb=''(0), cmp=-1
a=two , b=four , Ea=''(0), Eb=''(0), cmp=0
Use of uninitialized value in length at sort_junk.pl line 21.
Use of uninitialized value in length at sort_junk.pl line 21.
one
three
two
four

one
three
two
four