Latest web development tutorials

Perl subroutine (function)

Perl subroutine that is user-defined function.

Perl subroutine that is a piece of code to perform special tasks separation, it can make to reduce duplication of code and make the program easy to read.

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

sub subroutine{
   statements;
}

Subroutine call syntax:

subroutine( 参数列表 );

Perl 5.0 in the following versions subroutine call as follows:

&subroutine( 参数列表 );

In the new version, although it supports the call method, but not recommended.

Next we look at is a simple instance:

#!/usr/bin/perl

# 函数定义
sub Hello{
   print "Hello, World!\n";
}

# 函数调用
Hello();

The above program, the output is:

Hello, World!

Passing parameters to subroutines

Perl subroutine can accept multiple parameters and other programming, use the special array @_ subroutine parameters indicated.

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

Whether parameters are scalar or array type, the user of the parameter passed to the subroutine, perl default by the reference call them.

#!/usr/bin/perl

# 定义求平均值函数
sub Average{
   # 获取所有传入的参数
   $n = scalar(@_);
   $sum = 0;

   foreach $item (@_){
      $sum += $item;
   }
   $average = $sum / $n;
   print '传入的参数为 : ',"@_\n";           # 打印整个数组
   print "第一个参数值为 : $_[0]\n";         # 打印第一个参数
   print "传入参数的平均值为 : $average\n";  # 打印平均值
}

# 调用函数
Average(10, 20, 30);

The above program, the output is:

传入的参数为 : 10 20 30
第一个参数值为 : 10
传入参数的平均值为 : 20

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

Passed to the subroutine list

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

But if we need to pass a scalar and array parameters, you need to list on the last parameter, as follows:

#!/usr/bin/perl

# 定义函数
sub PrintList{
   my @list = @_;
   print "列表为 : @list\n";
}
$a = 10;
@b = (1, 2, 3, 4);

# 列表参数
PrintList($a, @b);

The above program will merge the scalar and an array of output results:

列表为 : 10 1 2 3 4

We can pass to subprograms multiple arrays and hashes, but if it's passed multiple arrays and hashes, will lead to the loss of an independent identity. So we need to use the reference (the next section will introduce) to pass.

Hash passed to a subprogram

When the hash table is passed to the subroutine, it will be copied to @_ in the hash table will be to expand the list of key / value pairs.

#!/usr/bin/perl

# 方法定义
sub PrintHash{
   my (%hash) = @_;

   foreach my $key ( keys %hash ){
      my $value = $hash{$key};
      print "$key : $value\n";
   }
}
%hash = ('name' => 'w3big', 'age' => 3);

# 传递哈希
PrintHash(%hash);

The above program execution output is:

age : 3
name : w3big

Subroutine return value

A subroutine can be like other programming languages ​​use the return statement to return values.

If no return statement, then the last line of the subroutine statement as the return value.

#!/usr/bin/perl

# 方法定义
sub add_a_b{
   # 不使用 return
   $_[0]+$_[1];  

   # 使用 return
   # return $_[0]+$_[1];  
}
print add_a_b(1, 2)

The above program execution output is:

3

Subroutine we can return scalars, arrays and hashes, but in return multiple arrays and hashes, will lead to the loss of an independent identity. So we need to use the reference (the next section will introduce) to return multiple arrays, and functions.


Subroutine private variables

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

If we need to set private variables, usemy operator to set.

my operator creates lexically scoped variables, variables created with mysurvival place in the beginning of the statement until the end of the closing scope.

Scope refers to the closure may be in the region braces pair can be a file, can also be an if, while, for, foreach, 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); #  同时声明多个变量
}
#!/usr/bin/perl

# 全局变量
$string = "Hello, World!";

# 函数定义
sub PrintHello{
   # PrintHello 函数的私有变量
   my $string;
   $string = "Hello, w3big!";
   print "函数内字符串:$string\n";
}
# 调用函数
PrintHello();
print "函数外字符串:$string\n";

The above program execution output is:

函数内字符串:Hello, w3big!
函数外字符串:Hello, World!

Temporary assignment variables

We can use the local temporary values ​​for global variables, the scope of the original value after the exit is also back.

local variables defined in the main program does not exist, but exist in the subroutine and the subroutine subroutine call. When you define can give it a value, such as:

#!/usr/bin/perl

# 全局变量
$string = "Hello, World!";

sub Printw3big{
   # PrintHello 函数私有变量
   local $string;
   $string = "Hello, w3big!";
   # 子程序调用的子程序
   PrintMe();
   print "Printw3big 函数内字符串值:$string\n";
}
sub PrintMe{
   print "PrintMe 函数内字符串值:$string\n";
}

sub PrintHello{
   print "PrintHello 函数内字符串值:$string\n";
}

# 函数调用
Printw3big();
PrintHello();
print "函数外部字符串值:$string\n";

The above program execution output is:

PrintMe 函数内字符串值:Hello, w3big!
Printw3big 函数内字符串值:Hello, w3big!
PrintHello 函数内字符串值:Hello, World!
函数外部字符串值:Hello, World!

Static variables

state operators function is similar to C's static modifier, state keywords will become persistent local variables.

state also lexical variables, only the definition of the lexical variable domain is valid, for example:

#!/usr/bin/perl

use feature 'state';

sub PrintCount{
   state $count = 0; # 初始化变量

   print "counter 值为:$count\n";
   $count++;
}

for (1..5){
   PrintCount();
}

The above program execution output is:

counter 值为:0
counter 值为:1
counter 值为:2
counter 值为:3
counter 值为:4

Note 1: state can only create a closed-scoped variables inside the subroutine.

Note 2: state is introduced from Perl 5.9.4, it must be added before use to use.

Note 3: state can declare scalar, array, hash. But when declaring arrays and hashes, you can not initialize it (at least Perl 5.14 is not supported).


Subroutine call context

Subroutine calls, it will return to the values ​​of different types depending on the context, such as the following localtime () subroutine in scalar context returns the string in list context returns a list:

#!/usr/bin/perl

# 标量上下文
my $datestring = localtime( time );
print $datestring;

print "\n";

# 列表上下文
($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