Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access the last Perl hash key without using a temporary array?

Tags:

hash

perl

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)?

like image 994
Zaid Avatar asked Dec 03 '22 07:12

Zaid


1 Answers

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];
like image 155
friedo Avatar answered Jan 22 '23 08:01

friedo