Perl

Subroutines in Perl

When it is required to execute the same block of code multiple times in the script, it is better to define a subroutine or function with the code and call the subroutine when that block of code is required to execute. Perl supports subroutines like other programming languages. Perl creates the subroutine using the “sub” keyword and the Perl subroutine can return the value using a return statement. The methods of declaring different types of subroutines are shown in this tutorial.

Syntax:

The syntax of declaring the Perl subroutine is shown in the following. The name of the subroutine is defined after the “sub” keyword:

sub Name {

  <Perl Script>

}

The Perl subroutine can be called in different ways which are mentioned in the following:

  1. SubroutineName();
  2. &SubroutineName;

Perl Subroutine Examples

Declaring and calling the Perl subroutines for different purposes are shown in this part of the tutorial.

Example 1: Define the Subroutine without an Argument

Create a Perl file with the following script that declares a subroutine to print the value of a global variable by concatenating it with the value of a local variable. The “$str” variable is declared globally in the script. The “$text” variable is declared locally inside the subroutine.

#!/usr/bin/perl

use strict;

use warnings;

#Declare a string variable

my $str = "Perl Programming";

#Define the subroutine without any parameter

sub display_message {

  my $text = "Learn ";

  print "$text$str\n";

}

print "Output:\n";

#Call the subroutine

display_message();

Output:

The following output appears after executing the script:

p1

Example 2: Define the Subroutine with an Argument

Create a Perl file with the following script that declares a subroutine to read a number that is taken from the user as an argument value and find out whether the number is even or odd. After taking the input from the user, the chomp() function is used to remove the new line from the input value. Next, the check_num() function is called with the argument and the “shift” function is used inside the function to read the argument value. The return statement is used in the function to return the message to the function caller.

#!/usr/bin/perl

use strict;

use warnings;

print "Enter a number: ";

#Take input from the user

my $num = <>;

#Remove newline

chomp($num);

#Call the function with one argument

print check_num($num);

#Define the function

sub check_num{

  #Read the first argument value

  my $n = shift;

  #Check if the number is even or odd

  if($n % 2 == 0)

  {

    return "$n is even number.\n";

  }

  return "$n is odd number.\n";

}

Output:

The following output appears after executing the script with the input value of 78:

p2-1

The following output appears after executing the script with the input value of 55:

p2-2

Example 3: Return the Value from the Subroutine Implicitly

The Perl subroutine can return the value without using a return statement and this type of return is called “implicit return”. In this example, two numeric values are taken from the user and passed to the subroutine named calculate_average(). This subroutine reads the argument values using @_ with a “for” loop and return the average value of the arguments through the “$avg” variable.

#!/usr/bin/perl

use strict;

use warnings;

#Take two numbers from the user and remove the newline

print "Enter the first number: ";

my $num1 = <>;

chomp($num1);

print "Enter the second number: ";

my $num2 = <>;

chomp($num2);

#Call the function with two arguments

print "The average of $num1 and $num2 is ".calculate_average($num1, $num2)."\n";

#Define the function

sub calculate_average{

  my $sum = 0;

  my $counter = 0;

  #Read all arguments using loop

  for my $v (@_){

    $sum += $v;

    $counter++;

  }

  #Count the average value

  my $avg = $sum/$counter;

  #Return average value

  $avg;

}

Output:

The following output appears after executing the script with the argument values of 60 and 40:

p3

Example 4: Pass an Array as an Argument Value in the Subroutine

In this example, an array of six numbers is declared and passed as the argument in the subroutine named sum_of_array_values(). The argument value is stored in an array using @_ inside the subroutine. Next, the sum of this array values is calculated by a “for” loop and is printed.

#!/usr/bin/perl

use strict;

use warnings;

use Data::Dumper;

#Declare an array as a number

my @num_arr = (10, 7, 45, 23, 90, 45);

print "The array values:\n";

#Print the array values

print Dumper(\@num_arr);

#Declare the function that will calculate the sum of array values

sub sum_of_array_values{

  #Read the array from the argument

  my @arr = @_;

  my $sum = 0;

  #Calculate the sum of array values

  for(my $i = 0; $i <= $#arr; $i++)

  {

    $sum += $arr[$i];

  }

  print "The sum of array values is $sum\n";

}

#Call the function with an array as an argument

sum_of_array_values(@num_arr);

Output:

The following output appears after executing the script:

p4

Conclusion

The methods of using the Perl subroutines for different purposes are explained in this tutorial using multiple Perl scripts.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.