Search code examples
perlperl-data-structures

What is the data structure of this variable in perl?


I am new to perl and reading a code written in perl. A line reads like this:

$Map{$a}->{$b} = $c{$d};

I am familiar with hash looking like %samplehash and accessed as $samplehash{a}="b"

but what does the above line say about what is Map actually?


Solution

  • Given these variables:

    my $a = "apples";
    my $b = "pears";
    my %c = ("bananas" => 2);
    my $d = "bananas";
    my %Map;
    

    The assignment

    $Map{$a}->{$b} = $c{$d};
    

    Results in a hash looking like this:

    %Map = (
        "apples" => {
            "pears" => 2
        }
    );
    

    %Map is a hash, which after the assignment contains a hash ref through autovivification: If not already there, the inner hash ref is automatically created by Perl by accessing the element $Map{$a}->{$b} in the %Map hash.