2009-10-29 12 views
9

在perl 5.8.5中,如果我执行以下操作,则不会出现错误:为什么undef值在Perl中成为有效的数组引用?

use strict; 

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

这里发生了什么?打印出ref($a)的输出表明$a在某些时候变为有效的数组引用。但我从来没有明确地将$a设置为任何东西。

似乎很奇怪,如果没有我做任何事情,变量的内容可能会改变。

想,有人吗?

编辑:是的,我知道所有关于自动生存的知识。我一直认为必须在某个地方有一个任务来触发它,而不仅仅是一个参考。

+3

这是perl。奇怪很好,因为它很奇怪。 – 2009-10-29 13:30:23

+3

我不认为这很奇怪,只是为了节省一些声明。 – 2009-10-29 13:44:05

+3

@Stefano:为什么麻烦检查Perl的问题只为巨魔?它很单调乏味...... – Telemachus 2009-10-29 16:45:00

回答

11

Uri Guttman's article on autovivification被禁用。

一旦你知道它并且节省很多尴尬,它就没有什么奇怪的了。

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.

+0

后续问题。为什么这种自动生动:'我的$ a;我的@x = @ $ a'? – FMc 2009-10-29 14:38:06

+4

@FM:一般来说,只能从解引用中读取的东西不会自动生成,而可能会修改解除引用的东西却可以。 for循环是一些可能会修改的示例(因为$ el被别名到数组中,并且数组可能会通过它进行更改)。尽管这只是一个松散的规则;有一些粗糙的边缘。 – ysth 2009-10-29 15:50:23

+0

要小心患有下标的病例,即使只是从他们那里读取,也可能会发生autovivication – 2009-10-30 19:16:59

15

Auto-vivification是这个词。从链接:

Autovivification is a distinguishing feature of the Perl programming language involving the dynamic creation of data structures. Autovivification is the automatic creation of a variable reference when an undefined value is dereferenced. In other words, Perl autovivification allows a programmer to refer to a structured variable, and arbitrary sub-elements of that structured variable, without expressly declaring the existence of the variable and its complete structure beforehand.

In contrast, other programming languages either: 1) require a programmer to expressly declare an entire variable structure before using or referring to any part of it; or 2) require a programmer to declare a part of a variable structure before referring to any part of it; or 3) create an assignment to a part of a variable before referring, assigning to or composing an expression that refers to any part of it.

Perl autovivication can be contrasted against languages such as Python, PHP, Ruby, JavaScript and all the C style languages.

自动vivification可以no autovivification;

+0

我不断刷新本页,看到我很好奇的答案。哇,Perl真的很奇怪:) – Bartek 2009-10-29 13:31:13

+2

对我来说这似乎很自然。 – 2009-10-29 13:34:36

+0

这是Perl DWIM的美德(做我的意思)。 – spoulson 2009-10-29 14:00:30

相关问题