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

Variable scoping

Variables declared with my within a subroutine are local to that subroutine - for example;
  my $x = 12;
  print qq{Before the sub, \$x is $x\n};
  welcome();
  print qq{After the sub, \$x is $x\n};

  sub welcome {
     my $x = 24;
     print qq{Within the sub, \$x is $x\n};
  }
will print out
  Before the sub, $x is 12
  Within the sub, $x is 24
  After the sub, $x is 12

Usually in a subroutine you want to pass in some variables to process, and then return the results of that processing.