Perl subroutine (function)
Perl
subroutines are user-defined functions.
Perl
subroutine is a separate piece of code that performs a particulartask that reduces repetitive code and makes the program readable.
Perl
subroutines can appear anywhere in the program and the syntax format is as follows:
sub subroutine{
statements;
}
Call subroutine syntax format:
subroutine( parameter list );
The method to call subroutines below Perl version 5.0 is as follows:
&subroutine( parameter list);
On the new version, although this calling method is also supported, it is not recommended.
Next, let’s look at a simple example:
Example
#/ Usr/bin/perl # function definition subHello {print "Hello, World! N";}#
Function call Hello();
Execute the above program, and the output is as follows:
Hello, World!
Pass parameters to the subroutine
Perl
subroutines can accept multiple parameters like other programs, andsubroutine parameters use special arrays @\_
mark.
Therefore, the first parameter of the subroutine is $_[0]
the second parameter is $_[1]
, and so on.
No matter whether the parameter is scalar or array, when the user passes theparameter to the subroutine perl
, they are called by default as references.
Example
#/ Usr/bin/perl # Define the averaging function subAverage{#
Obtain all incoming parameters $n=scalar (@ _)$ Sum=0; Foreach $item (@ _) {$sum+=$item;} $average=$sum/$n;
The parameters passed in as' print 'are:', '@ _ n'# Print the entire array. The first parameter value is:
$_ [0] n "; # Print the first parameter print" The average value of the passed in parameters is: $average n "#
Print Average} # Call the function Average (10, 20, 30);
Execute the above program, and the output is as follows:
The parameters passed in are: 10 20 30
The first parameter value is: 10
The average value of the incoming parameters is: 20
Users can change the @\_
array to change the value of the corresponding actual parameter.
Pass a list to a subroutine
Due to @\_
a variable is an array, so 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 follows:
Example
#/ Usr/bin/perl # Define Functions subPrintList{my@list =@\_; The 'print' list is:
@List n ";} $a=10; @ b=(1,2,3,4); # List parameter PrintList ($a, @ b);
The above program merges scalars and arrays, and the output is as follows:
The list is: 10 1 2 3 4
We can pass multiple arrays and hashes to subroutines, but passing multiple arrays and hashes results in the loss of independent identities. So we need to use references (described in the next chapter) to pass them on.
Pass a hash to a subroutine
When a hash table is passed to a subroutine, it is copied to the @\_
the hash table will be expanded into a list of key / value combinations.
Example
#/ Usr/bin/perl#
Method definition subPrintHash {my (% hash)=@ _; foreachmy $key (keys% hash) {my $value=$hash {$key};
Print "$key: $value n";}}% Hash=('name '=>'runoob', 'age'=>3)#
Pass Hash PrintHash (% hash);
The output of the above program execution is as follows:
age : 3
name : runoob
Subroutine return value
Subroutines can be used like other programming languages return
statement to return the function value.
If you don’t use return
statement, the last line of the subroutine’s statement is returned.
Example
#/ Usr/bin/perl # Method Definition Subadd_ A_ B
{# Do not use return $ _ [0]+$ _ [1]; # Use
Return # return$_ [0]+$_ [1] ;} Printadd_ A_ B (1,2)
The output of the above program execution is as follows:
3
We can return scalars, arrays and hashes in subroutines, but when returning multiple arrays and hashes, it will result in the loss of independent identities. So we need to use references (described in the next chapter) to return multiple arrays and functions.
Private variables of the subroutine
By default Perl
all variables in are global variables, which means thatvariables can be called anywhere in the program.
If we need to set private variables, we can use the my
operator to set.
my
operator is used to create lexical scope variables through the my
the created variable lives at the beginning of the declaration until the end of the closed cooperative domain.
A closed scope can refer to an area within a pair of curly braces, a file, or a string of if
, while
, for
, foreach
, eval
.
The following example shows how to declare one or more private variables:
sub somefunc {
my $variable; # $variable Not visible outside method somefunc()
my ($another, @an_array, %a_hash); # Declare multiple variables simultaneously
}
Example
#/ Usr/bin/perl # Global variable $string="Hello, World!"#
Function definition subPrintHello {# PrintHello
The private variable of the function, my $string$ String="Hello,
Runoob! String inside the "; print" function: $string n ";}#
Call the function PrintHello(); Print "Out-of-function string: $string n";
The output of the above program execution is as follows:
Function string: Hello, Runoob!
Out-of-function string: Hello, World!
Temporary assignment of variables
We can use it. local
provide a temporary value for the global variable and return the original value after exiting the scope.
local
defined variable does not exist in the main program, but exists in the subroutine and the subroutine that the subroutine calls. You can assign a value to it when defining it, such as:
Example
#/ Usr/bin/perl # Global variable $string="Hello, World!"; SubPrintRunoob{#
PrintHello function private variable local $string$ String="Hello, Runoob!"#
The subroutine called by the subroutine PrintMe(); Print "PrintRunoob
Function string value: $string n ";} subPrintMe {print" PrintMe
Function string value: $string n ";} subPrintHello {print" PrintHello
String value inside function: $string n ";}#
Function call PrintRunoob(); PrintHello(); Print "Function external string value: $string n";
The output of the above program execution is as follows:
String value in PrintMe function: Hello, Runoob!
String value in PrintRunoob function: Hello, Runoob!
String value in PrintHello function: Hello, World!
Function external string value: Hello, World!
Static variable
state
function of the operator is similar to that in C static
modifier 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:
Example
#/ Usr/bin/perluse feature 'state'; SubPrintCount {state $count=0#
Initialize variable print 'counter
The value is: $count n "; $count++;} for (1.. 5) {PrintCount();}
The output of the above program execution is as follows:
The counter value is: 0
The counter value is: 1
The counter value is: 2
The counter value is: 3
The counter value is: 4
Note 1: state
only variables within a subroutine can be created with a closed cooperative domain.
Note 2: state
was introduced from Perl 5.9.4, so it must be added before use. use
.
Note 3: state
scalars, arrays, and hashes can be declared. However, arrays and hashes cannot be initialized when declaring them (at least not supported by Perl 5.14).
Subroutine call context
During a subroutine call, different types of values are returned according to the context, such as the following localtime()
subroutine that returns a string in a scalar context and a list in a list context:
Example
#!/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 output of the above program execution is as follows:
Sun Jun 12 15:58:09 2016
2106-6-12 15:58:9