Skip to content
Related Articles

Related Articles

Perl | Subroutines or Functions

View Discussion
Improve Article
Save Article
  • Last Updated : 13 Jul, 2018

A Perl function or subroutine is a group of statements that together perform a specific task. In every programming language user want to reuse the code. So the user puts the section of code in function or subroutine so that there will be no need to write code again and again. In Perl, the terms function, subroutine, and method are the same but in some programming languages, these are considered different. The word subroutines is used most in Perl programming because it is created using keyword sub. Whenever there is a call to the function, Perl stop executing all its program and jumps to the function to execute it and then returns back to the section of code that it was running earlier. One can avoid using the return statement.

Defining Subroutines: The general form of defining the subroutine in Perl is as follows-

sub subroutine_name
    # body of method or subroutine

Calling Subroutines: In Perl subroutines can be called by passing the arguments list to it as follows-


The above way of calling the subroutine will only work with Perl version 5.0 and beyond. Before Perl 5.0 there was another way of calling the subroutine but it is not recommended to use because it bypasses the subroutine prototypes.



# Perl Program to demonstrate the 
# subroutine declaration and calling
# defining subroutine
sub ask_user {
   print "Hello Geeks!\n";
# calling subroutine
# you can also use
# &ask_user();


Hello Geeks!

Passing parameters to subroutines: This is used to pass the values as arguments.This is done using special list array variables ‘$_’. This will assigned to the functions as $_[0], $_[1] and so on.


# Perl Program to demonstrate the 
# Passing parameters to subroutines
# defining subroutine
sub area 
    # passing argument    
    $side = $_[0];
    return ($side * $side);
# calling function
$totalArea = area(4);
# displaying result
printf $totalArea;



Advantage of using subroutines:

  • It helps us to reuse the code and makes the process of finding error and debug easy.
  • It helps in organizing the code in structural format.Chunks of code is organized in sectional format.
  • It increases the code readability.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!