Autovivification
   HOME

TheInfoList



OR:

In the
Perl Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offici ...
programming language, autovivification is the automatic creation of new arrays and hashes as required every time an undefined value is dereferenced. 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 autovivification can be contrasted against languages such as
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
,
PHP PHP is a general-purpose scripting language geared toward web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementation is now produced by The PHP Group ...
,
Ruby A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sa ...
, and many of the C style languages, where dereferencing null or undefined values is not generally permitted. It can be compared to the HTML standard's "named access on the window object" which results in corresponding globally scoped variables being automatically accessible to browser-based
JavaScript JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of Website, websites use JavaScript on the Client (computing), client side ...
.


Hashes

It is important to remember that autovivification happens when an undefined value is dereferenced. An assignment is not necessary. The debugger session below illustrates autovivification of a hash just from examining it: DB<1> x \%h 0 HASH(0x2f1a248) empty hash DB<2> x $h 0 undef DB<3> x \%h 0 HASH(0x2f1a248) 1 => HASH(0x2f1a260) 2 => HASH(0x29a3c68) 3 => HASH(0x2dc3038) empty hash DB<4> The debugger session below illustrates autovivification of a hash from assigning to an inner hash: DB<1> $h=1 DB<2> x \%h 0 HASH(0x83c71ac) 'A' => HASH(0x837d50c) 'B' => HASH(0x83c71e8) 'C' => HASH(0x83c7218) 'D' => 1 DB<3> Hashes several layers deep were created automatically without any declarations. Autovivification can prevent excessive typing. If Perl did not support autovivification, the structure above would have to be created as follows: DB<1> %h = (A => ) DB<2> x \%h 0 HASH(0x83caba4) 'A' => HASH(0x83cfc28) 'B' => HASH(0x83cab74) 'C' => HASH(0x83b6110) 'D' => 1 DB<3>


File and directory handles

Perl 5.6.1 and newer support autovivification of file and directory handles. Calling open() on an undefined variable will set it to a filehandle. According to perl561delta, " is largely eliminates the need for
typeglob The structure of the Perl programming language encompasses both the syntactical rules of the language and the general ways in which programs are organized. Perl's design philosophy is expressed in the commonly cited motto "there's more than one way ...
s when opening filehandles that must be passed around, as in the following example: for my $file ( qw(this.conf that.conf) ) use Carp; sub open_or_throw


Emulation in other programming languages


C++

The C++ Standard Library's associative containers (std::unordered_map and std::map) use operator[] to get the value associated to a key. If there is nothing associated to this key, it will construct it and value initialize the value. For simple types like int or float, the value initialization will be zero initialization. std::unordered_map> a; a the answer"push_back(42); // Autovivifies the a the answer"vector and then appends to it. Another example of counting occurrences of strings: std::unordered_map counts; while (auto& s = GetNextString()) A similar trick can be achieved with the insert() method, which returns an iterator to the element associated to the key, even if it already exists.


Python

Python's built-in dict class can be subclassed to implement autovivificious dictionaries simply by overriding the __missing__() method that was added to the class in Python v2.5. There are other ways of implementing the behavior, but the following is one of the simplest and instances of the class print just like normal Python dictionary objects. >>> class Tree(dict): ... def __missing__(self, key): ... value = self ey= type(self)() ... return value >>> # Common names by class, order, genus, and type-species >>> common_names = Tree() >>> common_names Mammalia''Primates'] Homo''H. sapiens'] = 'human being' >>> common_names >>> # Famous quotes by play, act, scene, and page >>> quotes = Tree() >>> quotes Hamlet'1] 3] = 'This above all: to thine own self be true.' >>> quotes


Ruby

Ruby hashes can take a block specifying an object to be returned for non-existing indexes. These can be used to implement autovivificious maps. irb(main):001:0> tree = proc => # irb(main):002:0> lupin = tree.call => irb(main):003:0> lupin express"3] = "stand and deliver" => "stand and deliver" irb(main):004:0> lupin =>


Java

Java Map has a method computeIfAbsent that can be used to emulate autovivificous maps. public static Function defaultDict(Map map, Supplier supplier) public static void main(String[] args)


PHP

PHP arrays are natively autovivificious. $arr = array(); $arr express"3] = "stand and deliver"; However, this only applies to assignment, and not array access.


JavaScript

ES6 ECMAScript (; ES) is a JavaScript standard intended to ensure the interoperability of web pages across different browsers. It is standardized by Ecma International in the documenECMA-262 ECMAScript is commonly used for client-side scripting o ...
introduces a new class that can be used to implement autovivification. With other features of JavaScript, this can be reduced to a single line of code: var tree = () => new Proxy(, ); // Test: var t = tree(); t.first.second.third = 'text'; console.log(t.first.second.third); // or t first''second'] third'


C#

C#, using indexers and C# 4.0 dynamics, class Tree // Test: var t = new Tree(); t first""second"] third"= "text"; Console.WriteLine(t first""second"] third"; DynamicObject can be used for implementing different syntaxes also, using System; using System.Collections.Generic; using System.Dynamic; class Tree : DynamicObject // Test: dynamic t = new Tree(); t.first.second.third = "text"; Console.WriteLine(t.first.second.third); // or, dynamic t = new Tree(); t first""second"] third"= "text"; Console.WriteLine(t first""second"] third";


See also

* Evaluation strategy *
Variable Variable may refer to: * Variable (computer science), a symbolic name associated with a value and whose associated value may be changed * Variable (mathematics), a symbol that represents a quantity in a mathematical expression, as used in many ...
*
Vivification Vivification is an operation on a description logic knowledge base to improve performance of a semantic reasoner. Vivification replaces a disjunction of concepts C_1 \sqcup C_2 \ldots \sqcup C_n by the '' least common subsumer'' of the concepts C ...


Notes

{{notelist


References


External links


perl561delta: File and directory handles can be autovivified

Autovivification in Perl: An In-Depth Tutorial


- emulate Perl's autovivification
A Use of the Y Combinator in Ruby
- Implements autovivification in Ruby with the Y Combinator.
Hash#autonew in the Ruby gem "facets" adds autovivification on hash reads

The Ruby gem "xkeys" facilitates nested structure traversal and autovivifies on array or hash writes
Perl Evaluation strategy Articles with example Perl code Articles with example Python (programming language) code Articles with example PHP code Articles with example Java code Articles with example C++ code Articles with example Ruby code