Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

hash

perl

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.

like image 754
Dancrumb Avatar asked Dec 02 '22 01:12

Dancrumb


1 Answers

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.

like image 162
Sinan Ünür Avatar answered Dec 05 '22 00:12

Sinan Ünür