Perl is known for allowing multiple different ways of expressing a solution! This article examines various techniques by which a function/subroutine in Perl can accept and process parameters. As an example, we will stick to a subroutine called add
that adds the 2 arguments passed to it and returns the sum.
Method #1:
sub add() { return $_[0] + $_[1]; }
This method is straight-forward: The parameters are elements of the array @_
, whose first 2 elements are $_[0]
and $_[1]
. We add them and return the sum back.
Method #2:
sub add() { my ($x, $y) = ($_[0], $_[1]); return $x + $y; }
In this case, we copy the 2 parameters to locals $x
and $y
and return their sum. Many people prefer to copy the parameters to locals immediately as the parameters are passed by reference, and any changes made to them can affect the original arguments!
Method #3:
sub add() { my ($x, $y) = @_[0,1]; return $x + $y; }
This is an improvisation over the previous one using an array slice instead of 2 individual scalars from within an array.
Method #4:
sub add() { my ($x, $y) = @_; return $x + $y; }
An even more simpler version than the previous one!
Method #5:
sub add() { my @x = @_; print $x[0] + $x[1]; }
In this version, we are copying all parameters into the local array @x
and then accessing the elements.
Method #6:
sub add() { my $x = shift (@_); my $y = shift(@_); return $x + $y; }
The shift
function will delete and return the first element of the specified array, using which we extract the parameters into locals $x
and $y
, and return their sum.
Method #7:
sub add() { my $x = shift; my $y = shift; return $x + $y; }
When no array is specified as an argument for shift, it automatically works on @_
, making this work just like the previous version.
Method #8:
sub add() { my $y = pop; my $x = pop; return $x + $y; }
The pop
function also deletes and returns an element from the specified array, but from the end. And just like shift
, if the array is not specified, it automatically works on @_
.
And this is how every C/C++/Java programmer will write the function:
int add(int x, int y) { return x+y; }
The world of Perl is colourful!