1/12/2022

Nested Data Structure in PERL


In PERL the two data structure i.e Array and Hash , both can be nested. There can be simple nesting as well as complex nesting. In this article we will understand the various nesting of PERL Data Structures through various explicit code examples and outputs.


Nested Arrays in PERL :

In the below example , we have nested three anonymous array inside an Array .  One thing I will make clear that the array which stay inside the nest , always the anonymous array.

Here goes the code :

As shown in the code the array as a whole can be printed using the Dumper module or by picking the element individually as : $NestedArray[0][1] .

Upon execution of the code it gives the below output :


Nested Referenced Arrays :

This example is a bit different from the above one. Here the holding nest i.e the mother array is a referenced-array. As shown in the code the array as a whole can be printed using the Dumper module or by picking the element individually as : $refNestedArray->[0][1] .  Here you can spot the difference.

Here goes the code :

Once executed it gives the below output :


Equivalence of Arrow Notation :

The Arrow Notation, which is used to access nested data structure elements , can interchangeably be used in two ways  as shown in the table below:


In the programmer's community the Arrow Notation in R.H.S Column is more popular due to its  Easier to Read & Easier to Visually Interpret format.

You can use which ever you feel easy to remember !

Nested Hash in PERL :

In the Nested Hash , can be created in the below ways :

Each Individual elements can be accessed as print $NestedHash{flintstones}->{lead}; or the entire nest  can printed with the Dumper Module.

Nested Referenced Hash in PERL :

The Above Code will change as below if we change the nest as the Referenced Hash :

Hope you can spot the differences with the previous code !


Hybrid Nesting :  Array of Hash

We can create the nest with one data structure and content of the nest with another kind of the data structure . Here goes our first hybrid nesting :

The Nest is an Array while the eggs in the nest are hashes .

Hybrid Nesting : Hash of Array 

Here The nest is a Hash while the eggs are Array :

Recommended Further Reading : 

https://perldoc.perl.org/perldsc

https://perldoc.perl.org/perllol

https://perldoc.perl.org/perlref

https://perldoc.perl.org/perlreftut 

The entire article is discussed in the below video :