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="Rasmus Villemoes, post: 4863092"] Let me see if I understand what's going on: The last two lines builds an array of refs. Each ref is a reference to an anonymous array with exactly two entries: a maybe-key and the length of $h{key} (or some large number). Then this array of refs is sorted according to the contents of the [1] entry of the ref'ed anonymous array, and finally one extracts the [0] entry from each anonymous array. Smart. Yes, that it is what I was trying to achieve. But I would expect that the allocation of memory for all these small anonymous arrays would be rather time-consuming, also. Thanks to everybody for your answers. They confirm perl's slogan, and it's nice to see the different approaches. For the time being I will use &&-expressions and apply a decreasing function to length() so that the overall comparison of existing keys ends up in ascending order. If no elements are longer than 9 this actually works: my @ks = qw(two three one four); my %h = ( one => 1, three => 333 ); for (sort { (exists $h{$b} && 10-length $h{$b}) <=> (exists $h{$a} && 10-length $h{$a}) } @ks) { print "$_\n" } [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
Perl
Perl Misc
Sorting based on existence of keys
Top