从现在开始,每天一点点……
子程序--perl
上一篇 /
下一篇 2011-06-25 09:49:18
/ 个人分类:perl基础
1.
当使用use strict编译命令时,perl会要求你一定要用my来声明每个新的变量 #!/usr/bin/perl
use strict;
sub sum_of_fred_and_barney{
print "hey,you called the sum_of_fred_and_barney subroutine.\n";
return $fred + $barney; #从子程序种立刻返回某个值,若没有return会 将子程序最后执行的表达式的直返回;
print;
}
my $fred = 3;
my $barney = 4;
my $wilma = &sum_of_fred_and_barney;
print "wilma is $wilma.\n";
my $betty = &sum_of_fred_and_barney;
print "betty is $betty.\n";
否则会有如下的错误提示:
Global symbol "$fred" requires explicit package name at ./chapter4.pl line 9.
Global symbol "$barney" requires explicit package name at ./chapter4.pl line 10.
Global symbol "$wilma" requires explicit package name at ./chapter4.pl line 11.
Global symbol "$wilma" requires explicit package name at ./chapter4.pl line 12.
Global symbol "$betty" requires explicit package name at ./chapter4.pl line 13.
Global symbol "$betty" requires explicit package name at ./chapter4.pl line 14.
2.
在my不使用()时,只能声明单个词法变量 my $fred; 正确
my ($fred, $barney); 正确
my $fred, $barney;错误
3.
当子程序与perl的内置函数不同名且子程序的声明放在子程序被调用之前时, 可以将子程序调用符号&以及参数的括号省略掉 #!/usr/bin/perl
sub division{
$_[0] / $_[1];
}
$quotient = division 10, 2;
print $quotient;
4.
在子程序中可以使用my操作符来创建私有变量,但每次调用这个字程序的时候, 这个私有变量就会被重新定义。使用state声明变量,可以在子程序多次调用期 间保留变量的值并将变量的作用域局限于子程序。(注意:不能初始化state声 明的数组和散列) #!/usr/bin/perl
use strict;
use 5.010;
running_sum( 5, 6 );
running_sum( 1..3 );
sub running_sum{
state $sum = 0;
state @numbers;
foreach my $number(@_){
push @numbers, $number;
$sum += $number;
}
say "the sum of (@numbers) is $sum";
}
输出结果是:
the sum of (5 6) is 11
the sum of (5 6 1 2 3) is 17
作业题目:求1到1000的和
#!/usr/bin/perl
use strict;
use 5.010;
running_sum(1..1000);
sub running_sum{
state $sum = 0;
state @numbers;
foreach my $number(@_){
push @numbers, $number;
$sum += $numbser;
}
say "the sum is $sum";
}
收藏
举报
TAG: