Passing Parameters to Subroutine

Summary: in this tutorial, you will learn how to pass parameters to the subroutine by references and by values, and learn the differences between them.

In general, passing parameters by references means that the subroutine can change the values of the arguments. The changes also take effect after the subroutine ends.

However, passing parameters by values means the subroutine only works on the copies of the arguments, therefore, the values of the arguments remain intact.

Passing parameters by references

As mentioned in the previous Perl subroutine tutorial, when you change the values of the elements in the argument arrays @_, the values of  the corresponding arguments change as well. This is known as the passing parameter by reference.

Let’s take a look at the following example:

#!/usr/bin/perl use warnings; use strict; my $a = 10; my $b = 20; do_something($a,$b); print "after calling subroutine a = $a, b = $b \n"; sub do_something{     $_[0] = 1;     $_[1] = 2; }
Code language: Perl (perl)

How the program works.

  • First, we defined a subroutine &do_something. Inside the subroutine, we changed the values of the first and second parameters through the argument array @_.
  • Second, we defined two scalar variables  $a and $b, and initialized their values to 10 and 20. We passed these variables to the  &do_something subroutine.
  • Third, we displayed the values of $a and $b after calling the subroutine. The value of $a and $b changed as expected.

Passing parameters by values

If you don’t want the subroutine to change the arguments, you need to create lexical variables to store the parameters. Inside the subroutine, you can manipulate these lexical variables that do not affect the original arguments. This is called passing parameters by values.

Let’s take a look at the following example:

#!/usr/bin/perl use warnings; use strict; my $a = 10; my $b = 20; do_something($a,$b); print "after calling subroutine a = $a, b = $b \n"; sub do_something{     my ($p1,$p2) = @_;     $p1 = 1;     $p2 = 2; }
Code language: Perl (perl)

Inside the  &do_something subroutine:

  • First, we declared two lexical variables  $p1 and  $p2 using the  my keyword, and assigned the passing parameters to these variables. Notice that those variables ($p1, $p2) only exist inside the subroutine, therefore, they are also referred to as private variables.
  • Second, we changed private variables $p1 and $p2 inside the subroutine. However, the values of the arguments  $a and  $b were not affected.

In this tutorial, we showed you how to pass parameters to subroutines by references and by values.

Was this tutorial helpful ?