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
- A backslash takes a reference:
\@primesand\%capitalare plain scalars. - The arrow reaches through:
$pref->[0]indexes,$cref->{Japan}looks up. @{$pref}restores the whole array;refnames what a reference holds.
Keywords and builtins used here
myprintrefscalaruse
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.
Step 1 of 3 in References & structures, step 19 of 27 in Language basics.