Forums
New posts
Search forums
Members
Current visitors
Log in
Register
What's new
Search
Search
Search titles only
By:
New posts
Search forums
Menu
Log in
Register
Install the app
Install
Forums
Archive
Archive
Perl
Perl Misc
Sorting based on existence of keys
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an
alternative browser
.
Reply to thread
Message
[QUOTE="sln, post: 4863101"] This is not a very clever idea. First, using numeric context in the hash. Given the first, second treating it as a string. Given the first and second, third is to treat it as a 10 digit string. Example: two => 2e10 in the hash becomes two => 20000000000 , length = 11 when it hits the length() function So as a general rule, sorting by length in numeric context is not a good idea. The fourth is that its not portable. There is two parts to this, one is forcing non-existing elements to the bottom, the other to sort the existing ones and bring to the top. These two parts have to be kept separate for portablity. for (sort { (exists $h{$b} && $h{$b}) <=> (exists $h{$a} && $h{$a}) } @ks) { print "$_\n" } ^^^^ This wont work if you decide to sort by value instead of length. The most portable approach is a scheme like this: length: !($xb & $xa) ? $xb cmp $xa : length $h{$a} <=> length $h{$b} !($xb & $xa) ? $xb cmp $xa : length $h{$b} <=> length $h{$a} value: !($xb & $xa) ? $xb cmp $xa : $h{$a} <=> $h{$b} !($xb & $xa) ? $xb cmp $xa : $h{$b} <=> $h{$a} or more complex: !($xb & $xa) ? $xb cmp $xa : func($h{$a},$h{$b}) Any scheme will work as long as there is true separation between parts. -sln [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
Perl
Perl Misc
Sorting based on existence of keys
Top