How to Pass Parameters to Subroutines in Perl
Unlike many other programming languages, when you write the code for subroutines in Perl, you do not include a list of parameters that the function accepts. However, if you know the function will receive one or more parameters, you still need to program the subroutine to use them. Any parameters passed to a Perl subroutine are stored in the "@_" array, which is a special list array. This basically means that every subroutine you create can accept any number of parameters, but how many you need and how you use them is determined by the subroutine's code.
Instructions
-
-
1
Open a Perl program file. Type the following code:
sub line {
$var = @_[0];
}
This subroutine uses the "@_" array to get the parameters, but only makes use of the first one. Calling either "line('Hello!');" or "line('Hello!', 'How are you?');" both print "Hello!" to the screen.
-
2
Type the following code:
sub addNums {
$total = 0;
for ($i = 0; $i < @_; $i++) {
$total = $total + @_[$i];
}
return $total;
}
This subroutine call makes use of all the parameters passed to it, regardless how many exist. Calling "addNums(2,3);" returns five, "addNums(2,5,3);" returns 10 and "addNums(6,2,4,4);" returns 16.
-
-
3
sub array {
local($parOne, $parTwo, $parThree);
($parOne, $parTwo, $parThree) = ($_[0], $_[1], $_[2]);
print "You passed $parOne, $parTwo and $parThree as parameters.";
}
This subroutine takes the first three parameters passed to it and assigns them to local variables. Using specific variable names in longer subroutines can make it easier to understand what each is for instead of using the generic @_ array.
-
4
Save the Perl program file and run it.
-
1