perl里,子例程采用可变长参数列表,因此参数的个数不再限制,体现出动态语言的优点。由于传递的是引用,所以可以在sub里改变它的值。
samle01.pl
#!/usr/bin/perl
sub sub_routine{
$_[0] = "hello"; $_[1] = 999;
print "sub_par1:$_[0]\n";
print "sub_par2:$_[1]\n";
}
my $par1 = "abcde";
my $par2 = 2;
print "main_par1:$par1\n";
print "main_par2:$par2\n";
&sub_routine($par1, $par2);
print "main_par1:$par1\n";
print "main_par2:$par2\n";
运行结果:
main_par1:abcde
main_par2:2
sub_par1:hello
sub_par2:999
main_par1:hello
main_par2:999
如果不想在子例程里改变参数的值,可以采用生命局部变量的方法。
sample02.pl
#!/usr/bin/perl
sub sub_routine{
my $par1 = $_[0];
my $par2 = $_[1];
$par1 .= "fghijklmn";
$par2 += 10000;
print "sub_par1:$par1\n";
print "sub_par2:$par2\n";
}
my $par1 = "abcde";
my $par2 = 2;
print "main_par1:$par1\n";
print "main_par2:$par2\n";
&sub_routine($par1, $par2);
print "main_par1:$par1\n";
print "main_par2:$par2\n";
运行结果:
main_par1:abcde
main_par2:2
sub_par1:abcdefghijklmn
sub_par2:10002
main_par1:abcde
main_par2:2