How can I access the last element of keys in a hash without having to create a temporary array?
I know that hashes are unordered. However, there are applications (like mine), in which my keys can be ordered using a simple sort
call on the hash keys. Hope I've explained why I wanted this. The barney/elmo example is a bad choice, I admit, but it does have its applications.
Consider the following:
my %hash = ( barney => 'dinosaur', elmo => 'monster' );
my @array = sort keys %hash;
print $array[$#{$hash}];
#prints "elmo"
Any ideas on how to do this without calling on a temp (@array in this case)?
print( (keys %hash)[-1]);
Note that the extra parens are necessary to prevent syntax confusion with print
's param list.
You can also use this evil trick to force it into scalar context and do away with the extra parens:
print ~~(keys %hash)[-1];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With