Autovivification

Autovivification

Autovivification is a unique feature of the Perl programming language involving the dynamic creation of data structures. Autovivification is the automatic creation of a reference when an undefined value is dereferenced. In effect, this causes access to an element of a nonexistent hash (associative array) or array to create both the hash or array, and all elements below the given index for the array.

This is in contrast to most other high level languages, in which hashes or arrays must be explicitly created before using. This includes Python, PHP, Ruby, JavaScript and all the C style languages.

Hashes

The debugger session below illustrates autovivification of a hash:

DB<1> $h{A}{B}{C}{D}=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 => {B => {C => {D => 1}) 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, " [t] his largely eliminates the need for typeglobs when opening filehandles that must be passed around, as in the following example: sub myopen { open my $fh, "@_" or die "Can't open '@_': $!"; return $fh; }

{ my $f = myopen("; # $f implicitly closed here }

See also

* Evaluation strategy
* Variable

External links

* [http://perldoc.perl.org/perl561delta.html#File-and-directory-handles-can-be-autovivified perl561delta: File and directory handles can be autovivified]
* [http://web.archive.org/web/20040518032606/http://sysarch.com/perl/autoviv.txt Autovivification in Perl: An In-Depth Tutorial]
* [http://moonbase.rydia.net/mental/blog/programming/ruby/autovivification.html Autovivification in Ruby] - emulate Perl's autovivification
* [http://blog.ntrippy.net/admin/articles/show/12 More Autovivification in Ruby] - Arbitrary Depth Hashes (dead link)


Wikimedia Foundation. 2010.

Игры ⚽ Поможем решить контрольную работу

Look at other dictionaries:

  • Reference (computer science) — This article is about a general notion of reference in computing. For the more specific notion of reference used in C++, see Reference (C++). In computer science, a reference is a value that enables a program to indirectly access a particular… …   Wikipedia

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”