typestar

References in Perl

How Perl points at arrays and hashes instead of copying them.

use strict;
use warnings;

my @primes  = (2, 3, 5, 7);
my %capital = (France => "Paris", Japan => "Tokyo");

# a backslash takes a reference; the arrow dereferences
my $pref = \@primes;
my $cref = \%capital;

print "first prime: $pref->[0]\n";
print "capital of Japan: $cref->{Japan}\n";
print "count: ", scalar @{$pref}, "\n";
print "ref types: ", ref($pref), " and ", ref($cref), "\n";

How it works

  1. A backslash takes a reference: \@primes and \%capital are plain scalars.
  2. The arrow reaches through: $pref->[0] indexes, $cref->{Japan} looks up.
  3. @{$pref} restores the whole array; ref names what a reference holds.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
387
Tokens
90
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 83 seconds.

Type this snippet

Step 1 of 3 in References & structures, step 19 of 27 in Language basics.

← Previous Next →