References and Nested Data
Passing References
A subroutine can receive a reference and read the data it points to.
reference argument
A reference argument lets a subroutine work with a shared data structure.
Passing References
pass_refs.pl
Replay: real traced execution (multi-file project)
use strict;
use warnings;
sub total_points {
my ($values_ref, $bonus) = @_;
my $total = $values_ref->[0] + $values_ref->[1] + $values_ref->[2];
$total = $total + $bonus;
return $total;
}
my $bonus = 1;
my $values_ref = [2, 4, 6];
my $total = total_points($values_ref, $bonus);
print "bonus=$bonus\n";
print "total=$total\n";
use strict;
use warnings;
sub total_points {
my ($values_ref, $bonus) = @_;
my $total = $values_ref->[0] + $values_ref->[1] + $values_ref->[2];
$total = $total + $bonus;
return $total;
}
my $bonus = 0;
my $values_ref = [2, 4, 6];
my $total = total_points($values_ref, $bonus);
print "bonus=$bonus\n";
print "total=$total\n";
use strict;
use warnings;
sub total_points {
my ($values_ref, $bonus) = @_;
my $total = $values_ref->[0] + $values_ref->[1] + $values_ref->[2];
$total = $total + $bonus;
return $total;
}
my $bonus = 3;
my $values_ref = [2, 4, 6];
my $total = total_points($values_ref, $bonus);
print "bonus=$bonus\n";
print "total=$total\n";
$bonus ← 1
11my $bonus→ 1 = 1; #@bonus=0, 312my $values_ref = [2, 4, 6];13my $total = total_points($values_ref, $bonus1);$bonus ← 1, $total ← 12
4sub total_points {5 my ($values_ref, $bonus→ 1) = @_;6 my $total→ 12 = $values_ref->[0] + $values_ref->[1] + $values_ref->[2];7 $total→ 13 = $total + $bonus1;8 return $total13;9}$total ← 13
12my $values_ref = [2, 4, 6];13my $total→ 13 = total_points($values_ref, $bonus1);1415print "bonus=$bonus1\n";16print "total=$total13\n";outputbonus=1 total=13
$bonus ← 0
11my $bonus→ 0 = 0;12my $values_ref = [2, 4, 6];13my $total = total_points($values_ref, $bonus0);$bonus ← 0, $total ← 12
4sub total_points {5 my ($values_ref, $bonus→ 0) = @_;6 my $total→ 12 = $values_ref->[0] + $values_ref->[1] + $values_ref->[2];7 $total12 = $total + $bonus0;8 return $total12;9}$total ← 12
12my $values_ref = [2, 4, 6];13my $total→ 12 = total_points($values_ref, $bonus0);1415print "bonus=$bonus0\n";16print "total=$total12\n";outputbonus=0 total=12
$bonus ← 3
11my $bonus→ 3 = 3;12my $values_ref = [2, 4, 6];13my $total = total_points($values_ref, $bonus3);$bonus ← 3, $total ← 12
4sub total_points {5 my ($values_ref, $bonus→ 3) = @_;6 my $total→ 12 = $values_ref->[0] + $values_ref->[1] + $values_ref->[2];7 $total→ 15 = $total + $bonus3;8 return $total15;9}$total ← 15
12my $values_ref = [2, 4, 6];13my $total→ 15 = total_points($values_ref, $bonus3);1415print "bonus=$bonus3\n";16print "total=$total15\n";outputbonus=3 total=15