I needed to create a variable hash data structure in perl. I eventually found this piece of code:
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:
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);
$p->{$item} = {} unless exists($p->{$item});
$p = $p->{$item};
print "AFTER:\n";
print Dumper(\%hash);
}
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?
source
share