Dancrumb
Dancrumb

Reputation: 27529

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

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.

Upvotes: 4

Views: 650

Answers (2)

Leonardo Herrera
Leonardo Herrera

Reputation: 8406

Just 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 also works:

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

Fun fact: it appears that Perl uses the same approach than the one used for each, but without the iterator reset catch.

Upvotes: 3

Sinan Ünür
Sinan Ünür

Reputation: 118118

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.

Upvotes: 16

Related Questions