next up previous contents index
Next: Variable scoping Up: Subroutines, functions, and modules Previous: Variable scoping   Contents   Index


Passing in variables

For passing in variables, Perl provides for you, within each subroutine, a special array called @_ which contains a list of all variables passed in when the subroutine is called. For example,
  my $x = 12;
  my $y = 13;
  welcome($x, $y);

  my ($q, $r) = (22, 23);
  welcome($q, $r);

  sub welcome {
     my ($a, $b) = @_;
     print qq{You passed in $a and $b\n};
  }
will print out
  You passed in 12 and 13
  You passed in 22 and 23
Note the use of my ($a, $b) = @_; to assign the list of variables passed into the sub (contained in @_) to the variables $a and $b whose scope is limited to that sub. If you pass in just one variable into a sub, you can use the construction
  my $x = 12;
  welcome($x);

  sub welcome {
    my ($a) = @_;
    print qq{You passed in $a\n};
  }
or
  sub welcome {
    my $a = shift @_;  # shift extracts the first member of an array
    print qq{You passed in $a\n};
  }
or even
  sub welcome {
    my $a = shift;
    print qq{You passed in $a\n};
  }
as, within a sub, by convention shift operates on the @_ if an array is not specified (within a main program, shift; used without an array argument will by default use the @ARGV array containing a list of command-line arguments used to call the program).

Subsections