In Perl, how do I get an arbitrary value from a hash?

Consider the filled hash:

%hash = ( ... ); 

I want to get the value from the hash; any value will do.

I would like to avoid

 $arbitrary_value = (values %hash)[0]; 

since I really don't want to create an array of keys, just to get the first one.

Is there a way to do this without creating a list of values?

NB: It doesn't have to be random. Any value will do.

Any suggestions?

EDIT: Suppose I don't know any of the keys.

+4
source share
2 answers

Use each :

 #!/usr/bin/env perl use strict; use warnings; my %h = qw(abcdef); my (undef, $value) = each %h; keys %h; # reset iterator; print "$value\n"; 

As pointed out in the comments, in particular, calling keys () in a void context resets the iterator without any additional overhead . This behavior has been since at least 2003 , when information was added to the documentation for keys and values .

+16
source

As an exercise, and using the %h variable provided by Sinan, the following works for me:

 my (undef, $val) = %h; print $val, "\n"; 

And, of course, the following works:

 print((%h)[1], "\n"); 

Interesting fact: Perl seems to use the same approach as for each , but without a reset catch iterator.

+3
source

All Articles