为什么使用键()而不是%{...}进行自动换肤? [英] Why does Autovivification occur with keys() and not %{..}?

查看:197
本文介绍了为什么使用键()而不是%{...}进行自动换肤?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我用 keys()找到的微妙之处。

This is a subtlety I found with keys().

$ perl -e 'use warnings; use strict; my $d = { "ab" => 1 }; my @e = keys(%{$d->{cd}});'

$ perl -e 'use warnings; use strict; my $d = { "ab" => 1 }; my %e = %{$d->{cd}};'
Can't use an undefined value as a HASH reference at -e line 1.

我为什么第一个代码段不会给出解引用错误感到非常疑惑。当我使用 Data :: Dumper 时,很清楚在第一个片段中 $ d-> {cd} ,是autovivified为 {}

I am most puzzled as to why the first snippet would not give an dereferencing error. When I use Data::Dumper, it becomes clear that in the first snippet, $d->{cd}, is autovivified to be {}.

为什么需要autovivify?我尝试阅读 perldoc ,找不到令人满意的答案。 keys 不会设置别名( $ _ 等),因此不需要perl认为 $ d-> {cd} 需要处于左值上下文中,是吗? (我理解表达式是否需要在左值环境中进行自动版本化,正如此处所述。

Why does keys need to autovivify? I tried reading the perldoc for it, could not find a satisfying answer. keys does not set an alias ($_, etc) so there is no need for perl to think $d->{cd} needs to be in lvalue context, is there? (I understand if the expression needs to be in lvalue context autovivification happens as explained here.

相关的信息 a>。

推荐答案

请注意,键的确可以是一个左值(设置散列元素的预期数量)。

Note that keys can indeed be an lvalue (setting the hash's expected number of elements).

但即使键本身并不在左值上下文中使用,它也会重置一个散列的迭代器。

But even if keys itself isn't used in an lvalue context, it has a side effect of resetting a hash's iterator.

所以它修改了散列,因此给出了左值上下文的取消引用,这使得它自动生效。

So it does modify the hash and so gives the dereference an lvalue context, which makes it autovivify.

这篇关于为什么使用键()而不是%{...}进行自动换肤?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆