I needed to build a variable depth hash data structure in perl. Eventually I 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. At no point in this code do I see \%hash value being reset and it appears that $p (which is a local variable) is reset on every loop. I could even see it with data dumper: Running:
#!/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 $p being a new variable every time.
How does \%hash gets build if $p is reset every time?