Passing Arguments in Subroutines
Learn how you can pass arguments to a subroutine in this lesson.
We'll cover the following
What are the arguments?
The parameters of a subroutine accept values passed to them when that subroutine is called. The values passed are referred to as arguments of a subroutine. There are some tasks that do not require any arguments, for instance when we ask someone to come upstairs, it is understood which floor we are talking about. But some tasks require additional pieces of information. For instance, when we ask someone to cook, we have to tell them how many people to prepare a meal for.
Let’s look at the structure of a subroutine when we have passed arguments to it:
What are parameters?
Parameters are passed in the subroutines. They are used to hold values during runtime of a subroutine. A user can pass multiple parameters into a subroutine, we can get them by using @_[0]
for the first parameter and @_[1]
for the second parameter and @_[2]
for the third parameter and so on as discussed in the above illustration.
Note: You need to pass an argument corresponding to every parameter.
Example
Now let’s look at an example below:
#subroutine with two parameterssub mySubroutine{$num1 = @_[0];$num2 = @_[1];print "The value assigned to num1 is $num1\n";print "The value assigned to num2 is $num2";}#calling subroutine and passing arguments to itmySubroutine(3,4);
Explanation
As you can see above, the value of the first parameter, 3
, is assigned to $num1
and the value of second parameter, 4
, is assigned to $num2
. The subroutine mySubroutine
then displays both of these values on the console.