Get the element from a hash
I’ve tripped on this simple question:
Having a perl hash %h, and knowing that is has only one element, how to get to this element as easily / as efficiently as possible? Of course, we suppose here that you don’t know the key corresponding to this element…
For example, having a hash
my %h=( 'key' => 'value' );
if you know that is has only one element, how to get the key? how to get the value? Here are some solutions that I’ve found.
Do you have a better (faster, or more readable) one?
die "I said 'only one element' !" if (%h>1);
my $elem;
# Some solutions to get the key:
$elem=join('',keys(%h)); # be carefull: this converts to string!
$elem=[keys(%h)]->[0];
$elem=[%h]->[0];
# Some solutions to get the value:
$elem=join('',values(%h)); # be carefull: this converts to string!
$elem=[values(%h)]->[0];
$elem=[%h]->[1];