- Two common means of passing arguments to subs
- Pass by value
- Pass by reference
- Perl allows either
- Arguments are passed into the @_ array
- @_ is the "fill in the blanks" array
- Usually should copy @_ into local variables
sub add_one { # Like pass by value
my ($n) = @_; # Copy first argument
return ($n + 1); # Return 1 more than argument
}
sub plus_plus { # Like pass by reference
$_[0] = $_[0] + 1; # Modify first argument
}
my ($a, $b) = (10, 0);
add_one($a); # Return value is lost, nothing changes
$b = add_one($a); # $a is 10, $b is 11
plus_plus($a); # Return value lost, but a now is 11
$b = plus_plus($a); # $a and $b are 12
|