Open In App

Perl | Autovivification in References

Improve
Improve
Like Article
Like
Save
Share
Report

Perl Reference is a way to access the same data but with a different variable. A reference in Perl is a scalar data type which holds the location of another variable. Another variable can be scalar, hashes, arrays, function name etc. Nested data structure can be created easily as a user can create a list which contains the references to another list that can further contain the references to arrays, scalar or hashes etc.
A reference is used to create complex data structures like arrays of arrays, hashes of hashes, hashes of arrays and so on. So, the programmer has to make a reference to each of these references that hold the value.

Autovivification is a feature in which if a reference is made to an undefined value in hashes or arrays, Perl creates a reference value for it automatically.
Autovivification helps the programmer to write an entire variable structure and use it rather than explicitly declaring the variable earlier. It also makes the code readable.

NOTE: If a variable containing undef is dereferenced as if it were a hash reference, a reference to an empty anonymous hash is inserted.

Syntax:

$variable = {
input1 =>
{
input2 => ‘value’
}
};

Example 1:




#!/usr/bin/perl
use warnings;
use strict;
  
my $test->{fullName}->{lastName} = "Bong";
  
print $test, "\n"; # HASH(0x169af30)
print $test->{fullName},, "\n"; # HASH(0x16b9e48)
print $test->{fullName}->{lastName}, "\n"; # Bong


Output :

HASH(0x169af30)
HASH(0x16b9e48)
Bong

Example 2:




#!/usr/bin/perl
use warnings;
use strict;
  
my $anime->{manga}->{artist} = "One Piece";
  
print $anime, "\n"; # HASH(0x2405f30)
print $anime->{manga},, "\n"; # HASH(0x2424e48)
print $anime->{manga}->{artist}, "\n"; # One Piece


Output :

HASH(0x2405f30)
HASH(0x2424e48)
One Piece


Last Updated : 09 Sep, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads