Consider a populated hash:
%hash = ( ... );
I want to retrieve a value from the hash; any value will do.
I'd like to avoid
$arbitrary_value = (values %hash)[0];
since I don't really want to create an array of keys, just to get the first one.
Is there a way to do this without generating a list of values?
NB: It doesn't need to be random. Any value will do.
Any suggestions?
EDIT: Assume that I don't know any of the keys.
Use each
:
#!/usr/bin/env perl
use strict; use warnings;
my %h = qw(a b c d e f);
my (undef, $value) = each %h;
keys %h; # reset iterator;
print "$value\n";
As pointed out in the comments, In particular, calling keys() in void context resets the iterator with no other overhead. This behavior has been there at least since 2003 when the information was added to the documentation for keys and values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With