Subroutine / Function

                                                                                                                         

 

Subroutine /Function:

  • Every language have their inbuilt functions like (print ,sort , keys , values in PERL) and provide the facility to create the function according to user requirement.

PERL calls user-defined functions “subroutines” or “subs”.

  • A Perl subroutine or function is a group of statements that together perform a task.
  • To handle a large code you can divide your task/code in functions, but logically the division usually is so each function performs a specific task.

 

Creating a subroutine:

  • To create a PERL subroutine, you use the keyword sub followed by the subroutine name and the code for that subroutine in curly braces:

sub sub_name {

      statements…

}

  • Subroutine names do not have any specific character first, and naming rules are the same as other variables in Perl.

Example:

Sum

$sum

%sum

 

Calling a subroutine:

  • Whenever you require subroutine within your code ,you can use by calling subroutine process.

Syntax: #To run a subroutine in Perl

&sub_name( list of arguments );

  • Subroutines can call other subroutines, or themselves recursively.

 

Where should I write subroutine :

  • Perl compiles your program before executing it, it doesn’t matter where you declare your subroutine.

Example:

#!/usr/bin/perl -w

# subroutine definition

sub Hello {

      print “Hello, World!\n”;

}

# subroutine call

&Hello();

Result:

Hello, World!

 

Passing argument to subroutine :

  • You can pass various type of arguments to a subroutine.
  • Those arguments can be accessed inside the function using the special functions ($_,@_).

Types of possible arguments:

  • Scalar
  • Array/list
  • Hash
  • File

 

Multiple arguments:

  • The args list can be composed of many arguments, all separated by commas: sub1 arg1, arg2, arg3;
  • There is no limit to the number of arguments.
  • You can mix argument types in the list passed to the subroutine:

sub1 $x1, @array1, $x2, @array2;

  • But passing more than one array or hash normally causes them to lose their separate identities.

 

Passing a List/array in argument:

  • Because the @_ variable is an array, it can be used to supply lists to a subroutine.
  • However, because of the way in which Perl accepts and parses lists and arrays, it can be difficult to extract the individual elements from @_.

Example:

#!/usr/bin/perl -w

        #Function definition

sub Average{

         # get total number of arguments passed.

         $n = scalar(@_);

         $sum = 0;

        foreach $item (@_) {

                     $sum += $item;

         }

       $average = $sum / $n;

         print “Average for the given numbers : $average\n”;

}

       Subroutine Calling :

# Function call

&Average(10, 20, 30);

Result:

Average for the given numbers : 20

 

Passing hash in subroutine argument:

  • When you supply a hash to a subroutine or operator that accepts a list, then hash is automatically translated into a list of key/value pairs.

Example:

#!/usr/bin/perl

      # Function definition

sub PrintHash  {

          my (%hash) = @_; foreach $item (%hash)

          print “Item : $item\n”; }

}

%hash = (‘name’ => ‘Tom’, ‘age’ => 19);

# Function call with hash parameter

&PrintHash(%hash);

Result:

Item : name

Item : Tom

Item : age

Item : 19

 

Returning a value from subroutine:

  • PERL subroutine allows to return a value with return keyword.
  • If you are not returning a value from a subroutine then whatever calculation is last performed in a subroutine is automatically also the return value.
  • You can return arrays and hashes from the subroutine like any scalar.
  • But returning more than one array or hash normally causes them to lose their separate identities.
  • So normally we will use references to return any array or hash from a function.

Example:

#!/usr/bin/perl –w

#Function definition

sub Average{

        #get total number of arguments passed.

       $n = scalar(@_);

       $sum = 0;

       foreach $item (@_) {

                 $sum += $item;

        }

        $average = $sum / $n;

        return $average;

}

# Function call

$num = &Average(10, 20, 30);

print “Average for the given numbers : $num\n”;

 

Returning Array/hash:

  • You can return any hashes and arrays:

sub sub1 {

          statements…

          return @array;

           statements…

}

————————————

Calling:

@rev=reverse(sub1(@array));

  • In this code, an array is returned from the sub and reversed in the body of the Perl script, then stored in a new array variable

 

WARNING

Passing multiple arrays or hashes:

  • You might think you could pass more than one array or hash in the same manner:

sub multiple_arg

{ (@array1, @array2)=@_; print @array1, @array2;}

  • however this will not work as @_ will hold the two arrays together and there is no way to break them into two separate arrays in the subroutine.
  • There is no indication where one array ends and the next starts. In this case, @array1 would have the entire @_ contents and @array2 is empty.

 

Passing multiple arrays or hashes:

  • You can pass one array and a mix of scalars without problem as long as the array or hash is the last assigned element.
  • The scalars will be properly assigned from the @_ array and everything else goes in the array:

sub sub1 {

       ($x1, $x2, $x3, @array1)=@_;

       statements…;

}

 

Private variable in subroutine:

  • By default, all variables in Perl are global variables which means they can be accessed from anywhere in the program.
  • But PERL allows you to create private variables called lexical variables at any time.
  • Use my /local operator to declare private variable.
  • The my operator confines a variable to a particular region of code in which it can be used and accessed.
  • Outside that region, this variable can not be used or accessed. This region is called its scope.
  • A lexical scope is usually a block of code with a set of braces around it, such as those defining the body of the subroutine or those marking the code blocks of IF, WHILE, FOR, FOREACH, AND EVAL STATEMENTS.

Syntax:

sub sub1 {

my $var1;

# $var1 is invisible outside sub1()

my ($another, @an_array, %a_hash);

# declaring many variables at once

}

 

Difference between global and private variables:

#!/usr/bin/perl

# Global variable

$string = “Hello, World!”;

# Function definition

sub PrintHello {

# Private variable for PrintHello function

my $string;

$string = “Hello, Perl!”;

print “Inside the function $string\n”;

}

# Function call

&PrintHello();

print “Outside the function $string\n”;

Result:

Inside the function Hello, Perl!

Outside the function Hello, World!

 

Temporary values via LOCAL():

  • The local is mostly used when the current value of a variable must be visible to called subroutines.
  • Variable can be declared with local keyword.
  • A local just gives temporary values to global (meaning package) variables. This is known as dynamic scoping.

 

Example:

#!/usr/bin/perl

# Global variable

$string = “Hello, World!”;

sub PrintHello {

# Private variable for PrintHello function

local $string;

$string = “Hello, Perl!”;

PrintMe();

print “Inside the function PrintHello $string\n”;

}

sub PrintMe{

print “Inside the function PrintMe $string\n”;

}

       # Function call

&PrintHello();

print “Outside the function $string\n”;

Result:

Inside the function PrintMe Hello, Perl!

Inside the function PrintHello Hello, Perl!

Outside the function Hello, World!

 

State variables via state():

  • There another type of lexical variables which are similar to private variable but they maintain their state and they do not get reinitialized upon multiple calls of the subroutines.
  • These variables are defined using state operator and available starting from Perl 5.9.4

Example :

#!/usr/bin/perl

use feature ‘state’;

sub PrintCount{

state $count = 0;

# default value

print “Value of counter is $count\n”; $count++;}

for (1..5){

&PrintCount();

}

Result:

Value of counter is 0

Value of counter is 1

Value of counter is 2

Value of counter is 3

Value of counter is 4

Calling Subroutines from Other Subroutines:

  • you can call subroutines from other subroutines.
  • To call a subroutine from another subroutine, use the same subroutine-invocation syntax.
  • Subroutines that are called by other subroutines are known as NESTED SUBROUTINES.

Syntax:

sub sub1{

     statements…

}

sub sub2{

      statements..

     & sub1(arg)

}

Predefined Subroutines:

  • Perl 5 defines special subroutines that are executed at specific times.
    • The BEGIN subroutine, which is called when your program starts running.
    • The END subroutine, which is called when your program terminates.

1.Creating Startup Code Using BEGIN:

  • PERL allows you to create code that is executed when your program is started. To do this, create a special subroutine named BEGIN.

Example:

BEGIN {

print(“Hi! Welcome to Perl!\n”);

}

 

2.Creating Termination Code Using END:

  • PERL allows you to create code to be executed when your program terminates execution. To do this, define an END subroutine,

Example:

END {

print(“Thank you for using Perl!\n”);

}

  • The code contained in the END subroutine is always executed by your program, even if the program is terminated using die.

Example:

die(“Prepare to die!\n”);

END { print(“Ha! You can’t kill me!\n”);}

Result :

Prepare to die!

Ha! You can’t kill me!

                                                                                                                         

 

Leave a Reply

Your email address will not be published. Required fields are marked *