2011-10-19 38 views
4

考慮一個人口稠密的哈希:在Perl中,如何從散列中獲得任意值?

%hash = (...); 

我想要從哈希值;任何價值都可以做到。

我想避免

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

,因爲我真的不希望創建密鑰的陣列,剛拿到的第一個。

有沒有辦法做到這一點,而不會產生一個值列表?

注意:它不需要是隨機的。任何價值都可以做到。

有什麼建議嗎?編號: 假設我不知道任何密鑰。

+0

你知道鑰匙嗎? –

+0

已更新,以確認我不知道任何鍵 – Dancrumb

回答

16

使用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"; 

正如在評論中指出,In particular, calling keys() in void context resets the iterator with no other overheadThis behavior has been there at least since 2003當信息被添加到keysvalues的文檔中時。

+1

'scalar'太過分了。通過在標量上下文而不是無效上下文中對其進行評估,明確地做出更多的工作。雖然只是多一點點(創建一個帶有多個鍵的標量,然後將其釋放,然後釋放它) – ikegami

3

只是作爲練習,並使用%h變量思南提供了以下工作對我來說:

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

當然,以下也適用:

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

有趣的事實:看起來Perl使用的方法與用於each的方法相同,但沒有迭代器重置捕獲。