I’m still learning Perl, so there’s probably a more efficient way of doing this. I’m trying to take a hash, reverse it so $values => $keys, grab the new key (the old value) and then sort those keys.
Here’s the code in question:
foreach my $key (sort keys reverse %hash){
...}
What I’m expecting to happen is that reverse %hash will return a hash type, which is what keys is looking for. However, I get the following error:
Type of arg 1 to keys must be hash (not reverse)
I’ve tried putting parentheses around reverse %hash, but still get the same thing.
Any ideas why this wouldn’t work?
Perl functions can either return scalar values or lists; there is no explicit hash return type
(You can call
return %hashfrom a subroutine, but Perl implicitly unrolls the key-value pairs from the hash and returns them as a list).Therefore, the return value of
reverse %hashis a list, not a hash, and not suitable for use as an argument tokeys. You can force Perl to interpret this list as a hash with the%{{}}cast:You could also sort on the values of the hash by saying
Using
values %hashis subtly different from usingkeys %{{reverse %hash}}in thatkeys %{{reverse %hash}}will not return any duplicate values.