Define and Call a Subroutine in Perl


The general form of a subroutine definition in Perl programming language is as follows −

sub subroutine_name {
   body of the subroutine
}

The typical way of calling that Perl subroutine is as follows −

subroutine_name( list of arguments );

In versions of Perl before 5.0, the syntax for calling subroutines was slightly different as shown below. This still works in the newest versions of Perl, but it is not recommended since it bypasses the subroutine prototypes.

&subroutine_name( list of arguments );

Let's have a look into the following example, which defines a simple function and then call it. Because Perl compiles your program before executing it, it doesn't matter where you declare your subroutine.

Example

 Live Demo

#!/usr/bin/perl
# Function definition
sub Hello {
   print "Hello, World!\n";
}
# Function call
Hello();

Output

When the above program is executed, it produces the following result −

Hello, World!

Updated on: 29-Nov-2019

154 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements