Perl | Autovivification in References

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/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

chevron_right


Output :

HASH(0x169af30)
HASH(0x16b9e48)
Bong

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/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

chevron_right


Output :

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


My Personal Notes arrow_drop_up

Very helpful in nature, leave a like and a comment if you find my articles interesting

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.