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:
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 }