R
Rasmus Villemoes
Hi experts
Say I have an array @ks containing some strings which may or may not
exist as keys in a hash %h. How do I sort @ks such that the
non-existent keys come last (in any order), while the existing keys
are sorted using, say, length($h{$a}) <=> length($h{$a}) (that is not
really the property of the values I'll sort by, but that's not
important).
my @ks = qw(two three one four);
my %h = ( one => 1,
three => 333 );
for (sort { exists $h{$b} cmp exists $h{$a} ||
length $h{$a} <=> length $h{$b}} @ks) { print "$_\n" }
This produces the intended result, but under "use warnings;" one also
gets the expected warnings when $h{two} and $h{four} are compared in
the second line. Is there some smarter way to do this? (Also, I don't
know if cmp is the right tool for comparing boolean values).
Say I have an array @ks containing some strings which may or may not
exist as keys in a hash %h. How do I sort @ks such that the
non-existent keys come last (in any order), while the existing keys
are sorted using, say, length($h{$a}) <=> length($h{$a}) (that is not
really the property of the values I'll sort by, but that's not
important).
my @ks = qw(two three one four);
my %h = ( one => 1,
three => 333 );
for (sort { exists $h{$b} cmp exists $h{$a} ||
length $h{$a} <=> length $h{$b}} @ks) { print "$_\n" }
This produces the intended result, but under "use warnings;" one also
gets the expected warnings when $h{two} and $h{four} are compared in
the second line. Is there some smarter way to do this? (Also, I don't
know if cmp is the right tool for comparing boolean values).