11
votes

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
}

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.

Thoughts, anyone?

EDIT: 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.

2
This is perl. Oddity is fine, because it's odd. - Stefano Borini
I don't think it's odd, just a convenience to save some declarations. - user181548
@Stefano: why bother checking Perl questions only to troll? It's tedious... - Telemachus
Telemachus: Python programmers think that there is always only one true way for every situation. - Alexandr Ciornii
@Alexandr: Yes, I'm aware of the philosophy that "There should be one -- and preferably only one -- obvious way to do it." But is the One True Way to handle questions about Perl troll(post)? - Telemachus

2 Answers

16
votes

Auto-vivification is the word. From the link:

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.

Auto-vivification can be disabled with no autovivification;

11
votes

Read Uri Guttman's article on autovivification.

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

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.