2009-10-29 13 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

相關問題