next up previous contents
Next: The ref() Function Up: References Previous: Reference Types

Passing Parameters to Functions

When we introduced Functions we talked about passing parameters to functions. At the time, we were not able to pass more than one array to a function. This was because functions only see one array (the @_ array) when looking for parameters. References can be used to overcome this limitation.

Let's start off by passing two arrays into a function to show that the function only sees one array (pass_par.pl):

firstSub( (1..5), ("A".."E"));



sub firstSub {

    my(@firstArray, @secondArray) = @_ ;



    print("The first array is  @firstArray.\n");

    print("The second array is @secondArray.\n");

}

This program displays:

The first array is  1 2 3 4 5 A B C D E.

The second array is .

Inside the firstSub() function, the @firstArray variable was assigned the entire parameter array, leaving nothing for the @secondArray variable. By passing references to @arrayOne and @arrayTwo, we can preserve the arrays for use inside the function. Very few changes are needed to enable the above example to use references (pass_ref.pl):

@array1  = (1..5);
@array2  = ("A".."E");

firstSub( \@array1,  \@array2);         # One



sub firstSub {

    my($ref_firstArray, $ref_secondArray) = @_;   # Two



    print("The first array is  @{$ref_firstArray}.\n");  # Three

    print("The second array is @{$ref_secondArray}.\n"); # Three

}
This program displays:

The first array is  1 2 3 4 5.

The second array is A B C D E.

Three things were done to make this example use references:

1.
In the line marked "One," backslashes were added to indicate that a reference to the array should be passed.
2.
In the line marked "Two," the references were taken from the parameter array and assigned to scalar variables.
3.
In the lines marked "Three," the scalar values were dereferenced. Dereferencing means that Perl will use the reference as if it were a normal data type-in this case, an array variable.

An alternative more modern way of achieving the same as above is to create a Perl Reference array using square brackets:

firstSub( [1..5], ["A".."E"] );


sub firstSub {

    my($ref_firstArray, $ref_secondArray) = @_;    # Two



    print("The first array is  @{$ref_firstArray}.\n");  # Three

    print("The second array is @{$ref_secondArray}.\n"); # Three

}

next up previous contents
Next: The ref() Function Up: References Previous: Reference Types
dave@cs.cf.ac.uk