Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding references in Perl

Tags:

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>) {
chomp;
my ($city, $country) = split /, /;
#$table{$country} = [] unless exists $table{$country};
push @{$table{$country}}, $city;

print @{$table{$country}};
}



__DATA__
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;
like image 595
BioRod Avatar asked Dec 04 '22 23:12

BioRod


1 Answers

You are declaring the hash %table. The declaration is when you tell Perl that there is a lexically scoped variable. Initialization is when you assign a value to a variable the first time. You did not initialize it, so Perl puts a default value. 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.

like image 120
simbabque Avatar answered Dec 28 '22 19:12

simbabque