BioRod BioRod - 9 months ago 64
Perl Question

Understanding references in Perl

I'm trying to understand the tutorial on references in Perl

perldoc perlreftut

So far with the code below, I'm initializing an empty hash with

my %table

Here is the whole program

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

my %table;

while (<DATA>) {
my ($city, $country) = split /, /;
#$table{$country} = [] unless exists $table{$country};
push @{$table{$country}}, $city;

print @{$table{$country}};

Chicago, USA
Frankfurt, Germany
Berlin, Germany
Washington, USA
Helsinki, Finland
New York, USA

Can somebody explain to me the line below because I'm confused since I see a reference (I think) here but it was initialized as a hash with %table.

push @{$table{$country}}, $city;

Answer Source

You are declaring the hash %table. The declaration is when you tell Perl that there is a lexically scoped variable. You did not initialize it, which is putting a value into the variable the first time. Because it's a hash, it starts out with an empty list (), which amounts to false.

You do have a dereference operator in this line.

push @{$table{$country}}, $city;

It says take the value $table{$country} as an array reference, dereference it, and then push $city into that array. There is a feature called auto-vivification that automatically creates the necessary array ref before the value is pushed.

So after the first round over the input, you now have this data structure:

%table = ( 'USA' => [ 'Chicago' ] )

%table is a hash, but the key USA inside that hash holds an array reference.

To create multi-level data structures in Perl, you need reference. But the first level does not need to be a reference. It can be a hash or an array.