Perl subroutine (function)


Perl subroutine is also a user-defined function.

The Perl subroutine is a separate piece of code that performs a special task, which can reduce duplicate code and make the program easy to read.

The Perl subroutine can appear anywhere in the program. The syntax is as follows:

sub subroutine{

Invoke subroutine syntax format:

subroutine( Parameter List );

The method of calling a subroutine in the following versions of Perl 5.0 is as follows:

&subroutine( Parameter List ) ;

On the new version, although the calling method is also supported, it is not recommended.

Next, let's look at a simple example:


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

Execute the above program, the output is:

Hello, World!

Passing parameters to subroutines

Perl subroutines can accept as many arguments as other programming, and subroutine arguments are marked with a special array @_.

The first argument to the subroutine is $_[0], the second argument is $_[1], and so on.

When the argument is scalar or array, when the user passes the argument to the subroutine, perl calls them by reference by default.


#!/usr/bin/perl # Define the averaging function sub Average{ # Get all incoming parameters $n = scalar (@_); $sum= 0 ; foreach $item (@_){ $sum += $item; } $average= $sum / $n; Print 'passed argument is : ',"@_\n"; # print the entire array Print "The first parameter value is: $_[0]\n"; # print the first parameter Print "The average value of the passed parameters is: $average\n"; # print average } # call function Average(10, 20, 30);

Execute the above program, the output is:

The parameters passed in are   : 10  20 30
The first parameter value is  : 10
The average value of the incoming parameters is : 20

The user can change the value of the corresponding actual parameter by changing the value in the @_ array.

Passing a list to a subroutine

Since the @_ variable is an array, it can pass a list to a subroutine.

But if we need to pass in scalar and array parameters, we need to put the list on the last parameter, as shown below:


#!/usr/bin/perl #definition function sub PrintList{ my @list = @_; print "List is: @list\n"; } $a= 10 ; @b = ( 1, 2, 3, 4); # list parameter PrintList($a , @b);

The above program merges the scalar and the array, and the output is:

list is : 10 1 2 3 4

We can pass multiple arrays and hashes to a subroutine, but when we pass in multiple arrays and hashes, we will lose the separate identity. So we need to pass the reference (described in the next section).

Passing a hash to a subroutine

When a hash table is passed to a subroutine, it is copied into @_ and the hash table is expanded into a list of key/value combinations.


#!/usr/bin/perl # Method Definition sub PrintHash{ my (%hash) = @_; foreach my $key ( keys %hash ){ my $value = $hash{$key}; print "$key : $value\n"; } } %hash= ( 'name' => 'welookups', 'age' => 3); # Pass Hash PrintHash(%hash );

The above program execution output is:

age : 3
Name : welookups

Subroutine return value

A subroutine can return a function value using a return statement like any other programming language.

If no return statement is used, the last line of the subroutine will be the return value.


#!/usr/bin/perl # Method Definition sub add_a_b{ # Don't use return $_[0 ]+$_[1]; # Use return # return $_[0]+$_[1]; } print add_a_b(1, 2)

The above program execution output is:


In a subroutine we can return scalars, arrays, and hashes, but when multiple arrays and hashes are returned, it will result in the loss of a separate identifier. So we need to use a reference (described in the next section) to return multiple arrays and functions.

Private variable of subroutine

By default, all variables in Perl are global variables, which means that variables can be called anywhere in the program.

If we need to set a private variable, we can use the my operator to set it.


my operator is used to create lexical scope variables, and variables created with my survive at the beginning of the declaration until the end of the scope is closed.

Closed scope can refer to an area in curly braces, either a file or an if, while, for, foreach, eval string.

The following example demonstrates how to declare one or more private variables:

sub somefunc {
   my $variable; # $variable is not visible outside the method somefunc()
   my ( $another, @an_array, %a_hash); # Declare multiple variables at the same time


#!/usr/bin/perl # global variables $string = " Hello, World!"; #function definition sub PrintHello{ # Private variables for the PrintHello function my $string; $string = " Hello, welookups!"; print "In-function string:$string\n"; } # calling function PrintHello(); print "Out-of-function string:$string\n";

The above program execution output is:

Function string:Hello, welookups!
Out-of-function string:Hello, World!

temporary assignment of variables

We can use local to provide a temporary value for the global variable and return the original value after exiting the scope.

The variable defined by local does not exist in the main program, but exists in the subroutine and the subroutine called by the subroutine. You can assign values ​​to them when you define them, such as:


#!/usr/bin/perl # global variables $string = " Hello, World!"; sub Printwelookups{ # PrintHello function private variable local $string; $string = " Hello, welookups!"; # subroutine called by subroutine PrintMe(); print "The string value in the Printwelookups function:$string\n"; } sub PrintMe{ print "String value within the PrintMe function:$string\n"; } sub PrintHello{ print "The string value in the PrintHello function:$string\n"; } # function call Printwelookups(); PrintHello(); print "Function external string value:$string\n ";

The above program execution output is:

PrintMe in-function string Value:Hello, welookups!
Printwelookups string value inside the function:Hello, welookups!
PrintHello string value inside the function:Hello, World!
Function external string value:Hello, World!

Static variable


state operator function is similar to the static modifier in C, and the state keyword makes local variables persistent.

state is also a lexical variable, so it is only valid in the lexical scope in which the variable is defined, for example:


#!/usr/bin/perl use feature 'state'; sub PrintCount{ state $count = 0; # Initialization Variables print "counter value is:$count\n"; $count++; } for (1..5){ PrintCount(); }

The above program execution output is:

counter value:0 
Counter Value: 1
Counter Value: 2
Counter Value: 3
Counter Value: 4

Note 1: state can only create variables whose closed scope is inside the subroutine.

Note 2: State was introduced from Perl 5.9.4, so use must be added before use.

Note 3: state can declare scalars, arrays, and hashes. However, when an array and a hash are declared, they cannot be initialized (at least not supported by Perl 5.14).

Subprogram call context

During the subroutine call, different types of values ​​are returned depending on the context, such as the following localtime() subroutine, which returns a string in the scalar context and returns a list in the list context:


#!/usr/bin/perl # scalar context my $datestring = localtime( time ); print $datestring; print "\n"; # list context ($sec, $min,$hour,$mday,$mon, $year ,$wday,$yday,$isdst) = localtime(time); printf("%d-%d-%d %d:%d:%d",$year+ 1990,$mon+1,$mday,$hour,$min,$sec ); print "\n";

The above program execution output is:

Sun Jun 12 15:58:09 2016
2106-6-12 15:58:9

welookups is optimized for learning.© welookups. 2018 - 2019 All Right Reserved and you agree to have read and accepted our term and condition.