为什么 undef 值会成为 Perl 中的有效数组引用? [英] Why does an undef value become a valid array reference in Perl?

查看:48
本文介绍了为什么 undef 值会成为 Perl 中的有效数组引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 perl 5.8.5 中,如果我执行以下操作,则不会出现错误:

In perl 5.8.5, if I do the following, I don't get an error:

use strict;

my $a = undef;
foreach my $el (@$a) {
  ...whatever
}

这是怎么回事?打印出 ref($a) 的输出表明 $a 在某个时候变成了一个有效的数组引用.但我从来没有明确地将 $a 设置为任何东西.

What's going on here? Printing out the output of ref($a) shows that $a changes to become a valid array reference at some point. But I never explicitly set $a to anything.

一个变量的内容可以在我不做任何事情的情况下改变,这似乎有点奇怪.

Seems kind of odd that the contents of a variable could change without me doing anything.

有想法吗?

是的,我了解自动激活.我一直认为在触发它的过程中必须有一个任务,而不仅仅是一个参考.

Yes, I know all about auto-vivification. I always thought that there had to be a assignment somewhere along the way to trigger it, not just a reference.

推荐答案

阅读 Uri Guttman 关于自动活化的文章.

一旦你了解它,就没有什么奇怪的了,省去了很多尴尬.

There is nothing odd about it once you know about it and saves a lot of awkwardness.

Perl 首先计算一个解引用表达式并发现当前引用值是未定义的.它记录解引用的类型(标量、数组或散列)并分配该类型的匿名引用.Perl 然后在存储未定义值的地方存储新的引用值.然后继续进行中的解引用操作.如果你做嵌套的解引用表达式,那么从上到下的每一层都会导致它自己的autovivication.

Perl first evaluates a dereference expression and sees that the current reference value is undefined. It notes the type of dereference (scalar, array or hash) and allocates an anonymous reference of that type. Perl then stores that new reference value where the undefined value was stored. Then the dereference operation in progress is continued. If you do a nested dereference expression, then each level from top to bottom can cause its own autovivication.

这篇关于为什么 undef 值会成为 Perl 中的有效数组引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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