Perl Subroutines (Functions)
A Perl subroutine is a user-defined function.
A Perl subroutine is a separate piece of code that performs a specific task; it can reduce code duplication and make the program easier to read.
A Perl subroutine is a block of code that encapsulates a series of operations or calculations, and it can be called repeatedly so it can be reused throughout the program.
Perl subroutines help modularize a program, making the code easier to understand, maintain, and reuse.
Perl subroutines can appear anywhere in a program; the syntax format is as follows:
sub subroutine{
statements;
}
Syntax format for calling a subroutine:
subroutine( 参数列表 );
In versions below Perl 5.0, the method for calling a subroutine is as follows:
&subroutine( 参数列表 );
In newer versions, although this calling method is still supported, it is not recommended.
Next, let's look at a simple example:
Example
#!/usr/bin/perl
Function definition
sub
Hello
{
"
Hello, World!
\n
"
;
}
Function call
Hello
(
)
;
Running the above program, the output is:
Hello, World!
Passing Arguments to Subroutines
Perl subroutines can accept multiple arguments like other programming languages; subroutine arguments are denoted by the special array @_.
Therefore the first argument of the subroutine is $[0], the second argument is $[1], and so on.
Regardless of whether the arguments are scalars or arrays, when the user passes arguments to the subroutine, perl calls them by reference by default.
Example
#!/usr/bin/perl
Define a function to calculate the average
sub
Average
{
Get all the passed arguments
$n
=
scalar
(
@_
)
;
$sum
=
0
;
foreach
$item
(
@_
)
{
$sum
+=
$item
;
}
$average
=
$sum
/
$n; print 'The passed arguments are : ',"@\n"; # Print the entire array print "The first argument value is : $[0]\n"; # Print the first argument print "The average of the passed arguments is : $average\n"; # Print the average } # Call the function Average(10, 20, 30);
Running the above program, the output is:
传入的参数为 : 10 20 30
第一个参数值为 : 10
传入参数的平均值为 : 20
The user can change the value of the corresponding actual argument by changing the value in the @_ array.
Passing Lists to Subroutines
Since the @_ variable is an array, it can pass a list to the subroutine.
But if we need to pass scalar and array arguments, we need to put the list as the last argument, as shown below:
Example
#!/usr/bin/perl
Defining a function
sub
PrintList
{
my
@list
=
@_
;
"
The list is : @list
\n
"
;
}
$a
=
10
;
@b
=
(
1
,
2
,
3
,
4
)
;
List arguments
PrintList
(
$a
,
@b
)
;
The above program combines the scalar and the array, and the output is:
列表为 : 10 1 2 3 4
We can pass multiple arrays and hashes to a subroutine, but when passing multiple arrays and hashes, their individual identities are lost. So we need to use references (introduced in the next chapter) to pass them.
Passing Hashes to Subroutines
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 pairs.
Example
#!/usr/bin/perl
Method Definition
sub
PrintHash
{
my
(
%hash
)
=
@_
;
foreach
my
$key
(
keys
%hash
)
{
my
$value
=
$hash
{
$key
}
;
"
$key
:
$value
\n
"
;
}
}
%hash
=
(
'
name
'
=>
'
runoob
'
,
'
age
'
=>
3
)
;
Passing a hash
PrintHash
(
%hash
)
;
The output of the above program is:
age : 3
name : runoob
Return Values of Subroutines
Subroutines can use the return statement to return a function value, just like other programming languages.
If no return statement is used, the last line of the subroutine will be used as the return value.
Example
#!/usr/bin/perl
Method Definition
sub
add_a_b
{
Without using return
$_
[
0
]
$_
[
1
]
;
Using return
return $[0]+$[1];
}
add_a_b
(
1
,
2
)
The output of the above program is:
3
In Perl, references can be used to return multiple arrays and hashes. A reference is a scalar value that points to a data structure (such as an array or hash). Through references, we can package multiple arrays and hashes into a single return value passed to the calling program. This preserves the independence and integrity of the data structures.
Example
sub
return_multiple_data
{
my
@array1
=
(
1
,
2
,
3
)
;
my
@array2
=
(
'a'
,
'b'
,
'c'
)
;
my
%hash1
=
(
'key1'
=>
'value1'
,
'key2'
=>
'value2'
)
;
my
%hash2
=
(
'foo'
=>
'bar'
,
'baz'
=>
'qux'
)
;
return
(
@array1
,
@array2
,
%hash1
,
%hash2
)
;
}
my
(
$array_ref1
,
$array_ref2
,
$hash_ref1
,
$hash_ref2
)
=
return_multiple_data
(
)
;
Accessing Returned Data Using References
"Array 1: @{$array_ref1}\n"
;
"Array 2: @{$array_ref2}\n"
;
"Hash 1: "
.
join
(
", "
,
%
{
$hash_ref1
}
)
.
"\n"
;
"Hash 2: "
.
join
(
", "
,
%
{
$hash_ref2
}
)
.
"\n"
;
In the above code, the return_multiple_data subroutine returns references to four data structures.
In the calling program, we access the returned arrays and hashes by dereferencing these references, thereby preserving their independence and integrity.
The output is:
Array 1: 1 2 3
Array 2: a b c
Hash 1: key1, value1, key2, value2
Hash 2: foo, bar, baz, qux
Private Variables of Subroutines
By default, all variables in Perl are global, which means a variable can be accessed anywhere in the program.
If we need to set up private variables, we can use the my operator to set them.
my The operator is used to create lexically scoped variables; through my the variables created, they live from the point of declaration to the end of the enclosing scope.
An enclosing scope can be a region within a pair of curly braces, a file, or an if, while, for, foreach, or eval string.
The following example demonstrates how to declare one or more private variables:
sub somefunc {
my $variable; # $variable 在方法 somefunc() 外不可见
my ($another, @an_array, %a_hash); # 同时声明多个变量
}
Example
#!/usr/bin/perl
Global Variables
$string
=
"
Hello, World!
"
;
Function definition
sub
PrintHello
{
Private variables of the PrintHello function
my
$string
;
$string
=
"
Hello, Runoob!
"
;
"
String inside the function:
$string
\n
"
;
}
Calling a function
PrintHello
(
)
;
"
String outside the function:
$string
\n
"
;
The output of the above program is:
函数内字符串:Hello, Runoob!
函数外字符串:Hello, World!
Temporary Assignment of Variables
We can use local to provide a temporary value for a global variable, restoring the original value after exiting the scope.
A variable defined by local does not exist in the main program, but exists in the subroutine and in subroutines called by that subroutine. It can be assigned a value when defined, for example:
Example
#!/usr/bin/perl
Global Variables
$string
=
"
Hello, World!
"
;
sub
PrintRunoob
{
PrintHello function private variable
local
$string
;
$string
=
"
Hello, Runoob!
"
;
A subroutine called by a subroutine
PrintMe
(
)
;
"
String value inside the PrintRunoob function:
$string
\n
"
;
}
sub
PrintMe
{
"
String value inside the PrintMe function:
$string
\n
"
;
}
sub
PrintHello
{
"
String value inside the PrintHello function:
$string
\n
"
;
}
Function call
PrintRunoob
(
)
;
PrintHello
(
)
;
"
String value outside the function:
$string
\n
"
;
The output of the above program is:
PrintMe 函数内字符串值:Hello, Runoob!
PrintRunoob 函数内字符串值:Hello, Runoob!
PrintHello 函数内字符串值:Hello, World!
函数外部字符串值:Hello, World!
Static variable
The state operator functions similarly to the static modifier in C; the state keyword makes a local variable persistent.
state is also a lexical variable, so it is only valid in the lexical scope where it is defined. For example:
Example
#!/usr/bin/perl
use feature
'
state
'
;
sub
PrintCount
{
state
$count
=
0
;
Initialize variables
"
counter value is:
$count
\n
"
;
$count
++;
}
for
(
1
.
.5
)
{
PrintCount
(
)
;
}
The output of the above program is:
counter 值为:0
counter 值为:1
counter 值为:2
counter 值为:3
counter 值为:4
Note 1: state can only create variables whose enclosing scope is inside a subroutine.
Note 2: state was introduced starting from Perl 5.9.4, so you must add use before using it.
Note 3: state can declare scalars, arrays, and hashes. However, when declaring arrays and hashes, they cannot be initialized (at least Perl 5.14 does not support this).
Subroutine Call Context
During a subroutine call, different types of values are returned depending on the context. For example, the following localtime() subroutine returns a string in scalar context and a list in list context:
Example
#!/usr/bin/perl
Scalar context
my
$datestring
=
localtime
(
time
)
;
$datestring
;
"
\n
"
;
List context
The value of $year is a count starting from the year 1900
(
$sec
,
$min
,
$hour
,
$mday
,
$mon
,
$year
,
$wday
,
$yday
,
$isdst
)
=
localtime
(
time
)
;
printf
(
"
%d-%d-%d %d:%d:%d
"
,
$year
1900
,
$mon
1
,
$mday
,
$hour
,
$min
,
$sec
)
;
"
\n
"
;
The output of the above program is:
Sun Jun 12 15:58:09 2016
2106-6-12 15:58:9