Passing Parameters to Subroutine (original) (raw)

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=a, b = a,b=b \n";

sub do_something{     $[0] = 1;     $[1] = 2; }`Code language: Perl (perl)

How the program works.

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=a, b = a,b=b \n";

sub do_something{     my ($p1,$p2) = @_;     $p1 = 1;     $p2 = 2; }`Code language: Perl (perl)

Inside the &do_something subroutine:

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

Was this tutorial helpful ?