A subroutine can calculate a value and send it back with return.

return value A return value is the result a subroutine gives back to its caller.

Return Values

price
return_values.pl
Replay: real traced execution (multi-file project)
use strict;
use warnings;

sub add_tax {
    my ($price) = @_;
    my $tax = 2;
    my $total = $price + $tax;
    return $total;
}

my $price = 8;
my $total = add_tax($price);

print "price=$price\n";
print "total=$total\n";
use strict;
use warnings;

sub add_tax {
    my ($price) = @_;
    my $tax = 2;
    my $total = $price + $tax;
    return $total;
}

my $price = 5;
my $total = add_tax($price);

print "price=$price\n";
print "total=$total\n";
use strict;
use warnings;

sub add_tax {
    my ($price) = @_;
    my $tax = 2;
    my $total = $price + $tax;
    return $total;
}

my $price = 12;
my $total = add_tax($price);

print "price=$price\n";
print "total=$total\n";
  1. $price ← 8

    11my $price→ 8 = 8; #@price=5, 1212my $total = add_tax($price8);
  2. $price ← 8, $tax ← 2, $total ← 10

    4sub add_tax {5    my ($price→ 8) = @_;6    my $tax→ 2 = 2;7    my $total→ 10 = $price8 + $tax2;8    return $total10;9}
  3. $total ← 10

    11my $price = 8; #@price=5, 1212my $total→ 10 = add_tax($price8);1314print "price=$price8\n";15print "total=$total10\n";
    outputprice=8
    total=10
  1. $price ← 5

    11my $price→ 5 = 5;12my $total = add_tax($price5);
  2. $price ← 5, $tax ← 2, $total ← 7

    4sub add_tax {5    my ($price→ 5) = @_;6    my $tax→ 2 = 2;7    my $total→ 7 = $price5 + $tax2;8    return $total7;9}
  3. $total ← 7

    11my $price = 5;12my $total→ 7 = add_tax($price5);1314print "price=$price5\n";15print "total=$total7\n";
    outputprice=5
    total=7
  1. $price ← 12

    11my $price→ 12 = 12;12my $total = add_tax($price12);
  2. $price ← 12, $tax ← 2, $total ← 14

    4sub add_tax {5    my ($price→ 12) = @_;6    my $tax→ 2 = 2;7    my $total→ 14 = $price12 + $tax2;8    return $total14;9}
  3. $total ← 14

    11my $price = 12;12my $total→ 14 = add_tax($price12);1314print "price=$price12\n";15print "total=$total14\n";
    outputprice=12
    total=14

Follow the Return

  1. $price starts as 8.
  2. add_tax($price) passes 8 into the subroutine.
  3. Inside the subroutine, $tax is 2.
  4. $total becomes 8 + 2, which is 10.
  5. return $total sends 10 back to the caller. | price | tax | returned total | | --- | --- | --- | | 8 | 2 | 10 | | 5 | 2 | 7 | | 12 | 2 | 14 |

Exercise: return_values.pl

Reproduce price=8 and total=10, then use the pinned price variants 5 and 12 to predict total=7 and total=14.