在 Perl 中,如何从哈希中获取任意值?
考虑一个填充的哈希:
%hash = ( ... );
我想从哈希中检索一个值;任何值都可以。
我想避免,
$arbitrary_value = (values %hash)[0];
因为我真的不想创建一个键数组,只是为了获得第一个。
有没有办法在不生成值列表的情况下执行此操作?
注意:它不需要是随机的。任何值都可以。
有什么建议吗?
编辑: 假设我不知道任何键。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
each
:正如评论中指出的,特别是,在 void 上下文中调用 keys() 会重置迭代器,而不会产生其他开销。 这种行为至少自 2003 年以来就一直存在,当时信息被添加到键 和 值。
Use
each
: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.
作为练习,使用 Sinan 提供的
%h
变量,以下内容对我有用:当然,以下内容也有效:
有趣的事实:看起来 Perl 使用与一个用于
each
,但没有迭代器重置捕获。Just as an exercise, and using the
%h
variable provided by Sinan, the following works for me:And of course, the following also works:
Fun fact: it appears that Perl uses the same approach than the one used for
each
, but without the iterator reset catch.