Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Perl | Autovivification in References

  • Last Updated : 09 Sep, 2019

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.


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

Example 1:

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 :


Example 2:

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 :

One Piece

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!