- 1.调取子程序,将sun 子程序不断相加,然后面调取值。
-
#!/usr/bin/perl -w
-
sub feiyang {
-
$n =1;#全局变量
-
print "sailor number $n!\n"
-
}
-
&feiyang;#第一次调取子程序
-
&feiyang;#第二次
-
sub sum_f_b{
-
print "you called the sum_f_b subroutine!\n";
-
$fred $barney;
-
}
-
#给变量赋值
-
$fred = 3;
-
$barney = 2;
-
$wsum = &sum_f_b;
-
print "\$wsum is $wsum. \n";
-
$betty = 3 * &sum_f_b;
-
print "\$betty is $betty \n";
-
输出结果:
-
-
]# perl sun.pl
-
sailor number 1!
-
sailor number 2!
-
you called the sum_f_b subroutine!
-
$wsum is 5.
-
you called the sum_f_b subroutine!
-
$betty is 15
-
-
2.向子程序传递参数
-
cat suncan.pl
-
sub max{
-
if ($_[0]>$_[1]){# 数组为第一个参数的索引值为0,以此类推。
-
$_[0];
-
}else {
-
$_[1]
-
}
-
}
-
$n = &max(1,2);#将1和2传递给max 程序进行对比,然后获取返回值打印出来
-
#&max;
-
print $n;
-
输出结果:
-
#]#perl suncan.pl
-
2
-
-
3.子程序中的私有变量
-
#Perl 默认创建的是全局变量,在任何地方都可以访问,用my 操作符创建私有变量,禁止全局访问。
-
#@_ 包含参数列表
-
#!/usr/bin/perl -w
-
sub max{
-
#my ($m,$n); #私有变量
-
#($m,$n)=@_;
-
my ($m,$n) = @_; #等同于 上面注释的两行
-
if($m > $n){ $m}else{$n}
-
}
-
-
完整例子:
-
-
#!/usr/bin/perl -w
-
-
sub max{
-
my ($m,$n) = @_; #== my ($m,$n); ($m,$n)=@_;
-
if($m > $n)
-
{ print "the \$m is :$m \n";}else{print "the \$n is:$n \n";}
-
}
-
-
&max(4,3);#为子程序传递参数,这时@_或默认读取这两元素自定义为数组,然后将其赋值给变量。
-
输出:
-
]# perl sunmy.pl
-
the $m is :4
4.可变的参数列表
#可以用if判断@_ 参数个数,因为Perl 默认会把任意长度的列表当做参数传给子程序,但这也会造成很多问题。
#上边完善后的脚本为
sub max{
#判断是否为两个,两个就进行比较。
if (@_ !=2){
$sum = @_; #定义变量来获取@_的参数个数。
print "Warning ! The \@_ numbers is $sum, &max should be two arguments!\n";
}
else{
my ($m,$n) = @_;
if($m > $n)
{ print "the \$m is :$m \n";}else{print "the \$n is:$n \n";}
}
}
#&max(4,3,5);# 分别用两个参数和三个参数的子程序 做实验,
&max(4,3);
输出:
当参数为三个时:
]# perl sunmy.pl
Warning ! The @_ numbers is 3, &max should get exactly two arguments!
当参数为两个时:
]# perl sunmy.pl
the $m is :4
5.更好的&max 子程序
$maxmum = &max(3,5,10,4,2);
sub max {
# print "The \$maxmum is : $maxmum ";
my ($myx_so_far) = shift @_;
foreach (@_){
if($_ > $max_so_far){
$max_so_far = $_;
}
}
print "The \$max_so_far is:\n $max_so_far \n";
}
6.my参数
#!/usr/bin/perl -w
foreach(1...10){
my ($square)= $_ * $_;
print "$_ squared is $square.\n";
}
7.return
#!/usr/bin/perl -w
my @names = qw/ aa bb cc dd ee ff gg hh kk /;
my $result = &which_element_is("cc",@names);
sub which_element_is {
my($what,@array)= @_;
foreach $once (0...$#array){
if ($what eq $array[$once]){
return $_;
#print "the what is :\n $what \n:the \@array is :@array.\n";
}
}
-1;
}
print "the result is :\n $result \n" ;
8.非标量返回值
#!/usr/bin/perl -w
sub list_f_fred_to_barney{
if($fred < $barney){
$fred..$barney;
} else {
reverse $barney..$fred;
}
return $c;
}
$fred= 11;
$barney = 6;
$c = &list_f_fred_to_barney;
print $c;