Search code examples
perlhash

Find key name in hash with only one key?


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?


Solution

  • A list slice should do it

    (keys %h)[0]
    

    keys returns a list, so just extract the first element of that list.