Creating a variable depth hash data structure in perl

I needed to create a variable hash data structure in perl. I eventually found this piece of code:


#!/usr/bin/perl -w
use strict;

my %hash;
my $value = "foo";
my @cats = qw(a b c d);

my $p = \%hash;
foreach my $item (@cats) {
 $p->{$item} = {} unless exists($p->{$item});
 $p = $p->{$item};
}

My question is how and why it works. I thought I knew how perl worked. In no case in this code do I see the \% hash value reset, and it seems that $ p (local variable) is reset in every loop. I even saw this with a data damper: Duration:


#!/usr/bin/perl
use warnings;
use strict;
use Data::Dumper;

my %hash;
my $value = "foo";
my @cats = qw(a b c d);

my $p = \%hash;
foreach my $item (@cats) {
 print "BEFORE:\n";
 print Dumper(\%hash);
 #print Dumper($p);
 $p->{$item} = {} unless exists($p->{$item});
 $p = $p->{$item};
 print "AFTER:\n";
 print Dumper(\%hash);
 #print Dumper($p);
}

And then uncommenting the line with

#print Dumper($p)
CLEARLY shows that $ p is a new variable every time.

How is the \% hash if $ p reset every time?

+3
source share
3 answers

$p "reset" ; , . hashref, {}, .

, , $p - , . %hash. , .

+5

, $p:

 ...
 print "AFTER:\n";
 $p->{'$p'} = 'is here!';
 print Dumper(\%hash);
 delete $p->{'$p'};
}

AFTER

AFTER:
$VAR1 = {
  'a' => {
    'b' => {
      'c' => {
        '$p' => 'is here!'
      }
    }
  }
};

AFTER:
$VAR1 = {
  'a' => {
    'b' => {
      'c' => {
        'd' => {
          '$p' => 'is here!'
        }
      }
    }
  }
};

, $p , , %hash.

+1

Want to see something cool? It does the same (only you will never see that it assigns hashref!)

my $p = \\%hash; # $p is a reference to a hashref
foreach my $item (@cats) {
    # because $p references a reference, you have to dereference
    # it to point to the hash.
    $p = \$$p->{$item} unless exists $$p->{$item};
}

The slot is autovivified , as soon as you refer to it, and when it receives the address as hashref, it creates this hashref.

+1
source

Source: https://habr.com/ru/post/1755810/


All Articles