考虑一个填充的哈希:
%hash = ( ... );
我想从哈希中检索一个值;任何价值都可以.
我想避免
$arbitrary_value = (values %hash)[0];
因为我真的不想创建一个键数组,只是为了获得第一个键.
有没有办法在不生成值列表的情况下执行此操作?
注意:它不需要是随机的.任何价值都可以.
有什么建议?
编辑:
假设我不知道任何键.
解决方法
使用
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 overhead.This behavior has been there at least since 2003将信息添加到keys和values的文档中.