next up previous contents index
Next: Returning variables Up: Passing in variables Previous: Passing in variables   Contents   Index


Variable scoping

There is an important aspect to variable scoping that is worth discussing here. Consider
my $x = 33;
print qq{\$x before the sub call is $x\n};
test_it($x);
print qq{\$x after the sub call is $x\n};

sub test_it {
  my $x = shift;
  print qq{The value of \$x passed in was $x\n};
  $x = 99;
  print qq{The sub has now modified \$x to be $x\n};
}
This will lead to
$x before the sub call is 33
The value of $x passed in was 33
The sub has now modified $x to be 99
$x after the sub call is 33
Note that the variable $x declared within the subroutine has scope only within that routine, and so altering the value within the subroutine doesn't affect the variable $x in the main program.

However, as we shall see later, often for convenience (and also memory considerations) one passes in references to variables. Consider doing so in the above example:

my $x = 33;
print qq{\$x before the sub call is $x\n};
test_it(\$x);
print qq{\$x after the sub call is $x\n};

sub test_it {
  my $xref = shift;
  print qq{The value of \$xref passed in was $$xref\n};
  $$xref = 99;
  print qq{The sub has now modified \$xref to be $$xref\n};
}
which will lead to the following:
$x before the sub call is 33
The value of $xref passed in was 33
The sub has now modified $xref to be 99
$x after the sub call is 99
Thus, passing in a variable by reference into a subroutine, and subsequently altering it's value, will alter the values of the corresponding variables in the calling program.