I'm confused! How is sort {$top_words{$b} <=> $top_words{$a}} different from reverse sort {$top_words{$a} <=> $top_words{$b}}?
Also how are the values being clobbered? I would understand this if we were 'reversing' the hash by creating a new hash where the values of the original hash were the keys of the derived hash. However I applied a reverse to a sort based on the values in the original hash. This is different from something like my %top_words = reverse %words;
| [reply] [d/l] [select] |
It's not different, but that's not what he did. First he passed his hash, which presumably had words as keys and numbers as values, to reverse, which happily treated it as a list and reversed the list, which he assigned to another hash, turning the reversed list back into a hash. For example:
my %hash = ('one' => 1, 'two' => 2, 'three' => 3, 'four-minus-one' =>
+3);
my %newhash = reverse %hash;
# %newhash now contains (1 => 'one', 2 => 'two', 3 => 'four-minus-one'
+)
# or
# (1 => 'one', 2 => 'two', 3 => 'three')
See, it turned the original hash into a list and reversed it. Since the last item in the list was a value, that became the first item in the reversed list, becoming a key, with the next-to-last item in the original list (that value's key) becoming its value, and so on. And if any value appeared twice in the original list, it can't appear more than once as a key in the new hash, so all but one of its matching keys will be clobbered. Also, you can't know which key/value pairs will get clobbered, since a hash is unordered by definition.
| [reply] [d/l] [select] |
That is very interesting. I can surely use this to benchmark the different algorithms. However, could you enlighten me on how the first part works? perldoc has nothing on chr... Thanks!
| [reply] |
chr gives the character corresponding to an ASCII value. 65 = 'A', 66 = 'B', and so on. In retrospect, I could have made my loop 65..90, but I think 1..26 makes it more obvious that I'm spanning the alphabet. Putting x4 after it just turns 'A' into 'AAAA' and so on, to make it more obvious that they're words.
| [reply] [d/l] [select] |