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?
Let's have a look at
Hashes and arrays are not as different as they seem. They are both closely related to lists. Using lists is the way they are initialized normally, and
=>
is mostly an alias for,
with the only difference that it treats its left operand quoted implicitly. Perl stops only if you forget the quotation of its right operand, so the following both lines will be accepted:Well, did you ever try this?
...or this:
The hash above may look a bit strange, but it's just a key with the value
undef
.Because it's most likely that you will ask how to access the single value, I suggest to use:
...or even simpler:
That's what we started with.
However, you must remember to reset the iterator if you ever want to use it on the same hash again. Either another
each
will do it, orkeys
will, and if used in a scalar context, will avoid creating a list. So you can reset it withSo you could do it like this:
But assuming it like reading JSON messages and stuff where you just want to read what's in the hash once and throw it away, it is probably the most succinct. However, if you want the variable right away, it's probably easier to do this:
[ 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.‐
A list slice should do it
keys
returns a list, so just extract the first element of that list.As you're using list context on both sides of the assignment operator, the first item in the keys list gets assigned to $key.