Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find key name in hash with only one key?

Tags:

hash

perl

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?

like image 852
Sandra Schlichting Avatar asked Aug 11 '11 14:08

Sandra Schlichting


People also ask

How do I get the first key of a hash in Perl?

my %h = ( secret => 1; );

How get key from hash value in Perl?

Extracting Keys and Values from a Hash variable The list of all the keys from a hash is provided by the keys function, in the syntax: keys %hashname . The list of all the values from a hash is provided by the values function, in the syntax: values %hashname . Both the keys and values function return an array.

How do you get the key of a hash in Ruby?

hash.fetch(key) { | key | block } Returns a value from hash for the given key. If the key can't be found, and there are no other arguments, it raises an IndexError exception; if default is given, it is returned; if the optional block is specified, its result is returned.


1 Answers

A list slice should do it

(keys %h)[0] 

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

like image 175
Marc B Avatar answered Sep 24 '22 14:09

Marc B