Perl 小骆驼 4章笔记 子程序

定义一个子程序
sub marine {
  $n+=1;
  print "hello, $n\n";
}

所有变量均是全局。

调用子程序
&marine

子程序最后一个被求值的表达式为返回值。

传参数
$n=&max(10, 15);

参数列表会自动的存放在@_中。也就是子程序参数的第一个值在$_[0],第二个在$_[1]。

sub max{
  if ($_[0]>$_[1]) {
    $_[0];
  }else{
    $_[1];
  }
}

my($m,$n); 创建私有变量
sub max{
  my($m,$n);
  ($m,$n)=@_;
  if ($m>$n) {$m} else {$n}
}

或者直接
my($m,$n)=@_;
几乎每一个子程序都由类似的语句开头。

判断参数个数
if (@_!=2) {
  print "&max should get exactly two arguments\n";
}

这样设计max,就不需要考虑参数个数了。
sub max {
  my($max_so_far)=shift @_;
  foreach (@_) {
    if ($_ > $max_so_far) {
      $max_so_far=$_;
    }
  }
  $max_so_far;
}

注意
my ($num)=@_; 列表,$num得到第一个参数
my $num=@_; 标量,得到参数的个数
记住,如果没有使用括号,my只定义一个变量。
my $fred,$barney; 错误,只定义了$fred
my($fred,$barney); 两个均定义了

如果希望更严格的语法监测,要
use strict;
这样对于每一个新的变量,使用my。

如果编译器在调用之前知道此子程序的定义,或者perl从语法中能知道这是一个子程序调用,则子

程序前的符号&可以省略。
如果子程序和perl一个内嵌程序通明,则必须使用&来调用它。因此,默认的,最好在函数调用时都

使用&。

课后习题:

1,2:

#!/usr/bin/perl
sub total{
  my($sum)=shift @_;
  foreach (@_) {
    $sum+=$_;
  }
  $sum;

}

my @fred=qw{ 1 3 5 7 9 };
my $fred_total=&total(@fred);
print "the total of \@fred is $fred_total.\n";
print "enter some numbers on separate lines:";
my $user_total=&total();
print "the total of those numbers is $user_total.\n";

my $test2=&total(1 .. 1000);
print "the total from 1 to 1000 is $test2";

 

3.

#!/usr/bin/perl

sub total{
  my($sum)=shift @_;
  foreach (@_) {
    $sum+=$_;
  }
  $sum;

}

sub average{
  my $number=@_;
  my($ave)=&total(@_) / $number;
  $ave;

}

sub above_average{
  my(@result);
  my($ave)=&average(@_);
  foreach (@_) {
    if ($ave  }
  @result;
}

my @fred=&above_average(1..10);
print "\@fred is @fred\n";
print "(should be 6 7 8 9 10)\n";
my @barney=&above_average(100,1..10);
print "\@barney is @barney\n";
print "

 




 

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/11903161/viewspace-688525/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/11903161/viewspace-688525/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值