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: 4863100"] RV> Let me see if I understand what's going on: The last two lines builds RV> an array of refs. Each ref is a reference to an anonymous array with RV> exactly two entries: a maybe-key and the length of $h{key} (or some RV> large number). Then this array of refs is sorted according to the RV> contents of the [1] entry of the ref'ed anonymous array, and finally RV> one extracts the [0] entry from each anonymous array. Smart. the concept is very old and this particular style is attributed to randal schwarz and called the schwarzian transform. my module Sort::Maker can generate this or the even faster GRT style. RV> Yes, that it is what I was trying to achieve. But I would expect that RV> the allocation of memory for all these small anonymous arrays would be RV> rather time-consuming, also. nope. you need to learn some algorithm theory before you make that claim. the malloc and key extraction stuff is O(N) which increases linearly. the actual sort comparisons are O(N log N) which increase much faster. so for short data sets, your will be faster but as the set size increases the ST will get faster until it blows away normal sorting. again, Sort::Maker has an article about this and its docs cover it too. besides the speed gain, the removal of redundant and confusing code makes this style much better for complex sorts. the map/sort/map is an idiom which is not hard to get but you have only one set of key extraction logic vs 2. RV> Thanks to everybody for your answers. They confirm perl's slogan, and RV> it's nice to see the different approaches. For the time being I will RV> use &&-expressions and apply a decreasing function to length() so that RV> the overall comparison of existing keys ends up in ascending order. If RV> no elements are longer than 9 this actually works: RV> my @ks = qw(two three one four); RV> my %h = ( one => 1, RV> three => 333 ); RV> for (sort { (exists $h{$b} && 10-length $h{$b}) <=> RV> (exists $h{$a} && 10-length $h{$a}) } @ks) { print "$_\n" } and you consider that clearer logic and code than the ST version? it will break on longer strings as you say which is a flaw. data changes and you have a bug waiting to happen. that is not good coding. uri [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
Perl
Perl Misc
Sorting based on existence of keys
Top