next up previous contents
Next: Passing Parameters by Reference Up: Functions Previous: Functions

Using the Parameter Array (@_)

All parameters to a function are stored in an array called @_. One side effect of this is that you can find out how many parameters were passed by evaluating @ in a scalar context.

For example, func2.pl:

firstSub(1, 2, 3, 4, 5, 6);

firstSub(1..3);

firstSub("A".."Z");



sub firstSub {

    $numParameters = @_ ;

    print("The number of parameters is $numParameters\n");

}

This program prints out:

The number of parameters is 6

The number of parameters is 3

The number of parameters is 26

Perl lets you pass any number of parameters to a function. The function decides which parameters to use and in what order. The @_ array is used like any other array.

Let's say that you want to use scalar variables to reference the parameters so you don't have to use the clumsy and uninformative $_ [0] array element notation. By using the assignment operator, you can assign array elements to scalars in one easy step.

For example, func3.pl:

areaOfRectangle(2, 3);

areaOfRectangle(5, 6);



sub areaOfRectangle {

    ($height, $width) = @_ ;



    $area = $height * $width;



    print("The height is $height. The width is $width.

        The area is $area.\n\n");

}

This program prints out:

The height is 2. The width is 3.

        The area is 6.



The height is 5. The width is 6.

        The area is 30.

The statement ($height,$width) = @_; does the array element to scalar assignment. The first element is assigned to $height, and the second element is assigned to $width. After the assignment is made, you can use the scalar variables to represent the parameters.



dave@cs.cf.ac.uk