Drew Kelson Drew Kelson - 6 months ago 18
Perl Question

Perl hash referencing

If anyone could help me out I would greatly appreciate it. Currently I am working on converting some old Perl scripts to C# but in doing so I keep coming across code in the following syntax:

$w{$x}->{y} = $z


I understand the basics of hash in Perl but I'm fairly new to Perl in general and I cannot find an example like this anywhere.

Is this just saving a reference to a value of a key in a hash?

Answer

Working backwards, it is assigning the value of $z to the key y of a hash reference, where that reference is assigned to key $x of a hash named %w.

perl -wMstrict -MData::Dumper -E 'my %h; my $x=1;  $h{$x}->{y}=3; print  Dumper \%h;'

$VAR1 = {
          '1' => {
                   'y' => 3
                 }
        };

In Perl, the values of list-type data structures can only be scalar items (single entities), so everything under the first level of a hash must be a reference. A reference is simply a scalar value that holds a 'pointer' to the item in question.

Comments