Find key name in hash with only one key?
Solution 1
A list slice should do it
(keys %h)[0]
keys
returns a list, so just extract the first element of that list.
Solution 2
my ($key) = keys %h;
As you're using list context on both sides of the assignment operator, the first item in the keys list gets assigned to $key.
Solution 3
I do not believe it is necessary to use the keys
function.
my ($key) = %h;
or
my $key = (%h)[0];
The hash inside the parens will be expanded to a list, then we can simply take the first element of that list, which is the key.
Solution 4
my @keys = keys %h;
my $key = $keys[0];
Solution 5
[ keys %h ]->[0]
will also do the disambiguation Joel mentions in an earlier comment. This code smells like it will cause problems though. If there is really only a single key/value pair, there might be a better way to handle the data.
At the least, I'd check to be sure the expectation is never violated silently. E.g.‐
keys %h == 1 or die "ETOOMANYKEYS";
print [ keys %h ]->[0], $/;
Sandra Schlichting
Updated on March 16, 2020Comments
-
Sandra Schlichting over 4 years
If I have a hash
my %h = ( secret => 1; );
and I know that is only is one key in the hash, but I don't know what it is called.
Do I then have to iterate through that hash
my $key; foreach my $i (keys %h) { $key = $h{$i}; }
Or are there a better way to get the name of the key?