Jump to content

Autovivification

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by 216.240.4.76 (talk) at 13:48, 1 November 2009 (→‎External links). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

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.

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("</etc/motd");
	print <$f>;
	# $f implicitly closed here
    }

See also