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="Uri Guttman, post: 4863076"] JG> my @ks = qw(two three one four); JG> my %h = ( one => 1, three => 333 ); JG> my @sorted = ( JG> (sort {length $h{$a} <=> length $h{$b}} grep {exists $h{$_}} @ks), JG> (grep {!exists $h{$_}} @ks) JG> ); all this confusing redundant code is annoying me. i left an exercise on doing this all one time but it seems i will have to answer it myself. i will assume length of a key will always be less than some large number which is how missing keys will sort late. this is an untested ST but Sort::Maker can generate this for you too. @sorted = map $_->[0], sort { $a->[1] <=> $b->[1] } map [ $_, exists($h{$_}) ? length $h{$_} : 9999999 ], @unsorted ; there is only one call to exists and length and it is much clearer what you mean to do. and Sort::Maker cleans up all the cruft and you only need the exists expression. the point is that you want to do key extraction/processing only one time both for speed and for clarity. perl6's sort supports this style and drops the $a/$b redundant stuff in general. uri [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
Perl
Perl Misc
Sorting based on existence of keys
Top