perl教程-子程序

今日新浪博客打不开,暂且mount到此处吧

点击打开链接

点击打开链接


@_ 在某个函数内,数组 @_ 包含传递给该函数的所有参数。
   在标量的上下文之中是指,数组元素的个数
 $_ 默认的输入/输出和格式匹配空间;也即默认省略的控制变量,
[akang@akang perl_practice]$ vi call_1
1.调用的例子1
#!/usr/bin/perl
use 5.012;
use strict;
#use Test::More;
sub hi{
    print "hello world!\n";
    say "HELLO WORLD!";
}

#&hi();
do hi();

[akang@akang perl_practice]$ ./call_1
Use of "do" to call subroutines is deprecated at ./call_1 line 11.
hello world!
HELLO WORLD
!
[akang@akang perl_practice]$ 

2.写一个名为&total的子程序,返回一列数字的和

#!/usr/bin/perl
my $sum;
sub total(){
    foreach (@_){
        $sum += $_;
    }
    return $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(<STDIN>);

print "The total of those numbers is $user_total.\n";

print "1..1000的和:", &total(1..1000), "\n";

[akang@akang per_practice]$ ./total
The total of @fred is 25.
Enter some numbers on separate lines: 1

The total of those numbers is 26.
1..1000的和:500526


3.在上面函数之后,列出大于均值的元素

sub average(){
    if (@_==0){
       return;
    }
    else{
    my $count=@_;
    my $sum= &total(@_);
    return $sum/$count;
    }

}
sub above_average(){
    my $average=&average(@_);
    my @list;#存放原列表处理结束之后结果存的列表
    foreach $element(@_){
        if ($element>$average){
            push @list,$element;
        }
    }
    return @list;
}

my @above_fred = &above_average(1 .. 10);
print "The above average of \@fred is: @above_fred\n";
-- INSERT --                                                                                      

  [akang@akang per_practice]$ ./total
The total of @fred is 25.
The above average of @fred is 6 7 8 9 10


4.

define用法:函数defined返回0、false或者非0、true。
此运算结果依赖于传递给它进行计算的参数的内容。
如果参数中不含有字符和数字值,则返回0;如果参数中包含一个字符或者数字值,则返回非0或者true值。if(x)true
这对于判断一个已经建立的数组中的每个元素是否已经定义非常有用。
当你将一些 资料 传入涵数(sub)时, 该涵数里就会有一个叫 @_ 的数组自动生成, 
并将你输入的资料存起. shift ; 其实就是 shift @_ 的意思.取输入参数自动生成数组的第一个元素呀

在子程序中可以使用my操作符来创建私有变量,但每次调用这个子程序的时候,这个私有变量都会被重新定义,使用state操作符来声明变量,便可以在子程序的多次调用间保留变量的值,并将变量的作用域局限于子程序中

[akang@akang per_practice]$ ./stat_define
hi lily
0
last:
Hi lily,you are the first person
hi amanda
1
Hi amanda,lily aslo here


per教程

shift在数组头部取出元素,所以剩下的数组是去掉头部元素之后的数组。

下面的例子是把输入的所有的数据,都放到列表,所以判断列表是否为空,而不是判断shift处理之后的

[akang@akang per_practice]$ ./stat_define_list
....
hi lily
you are the first person here
....lily
hi amanda
lily
you will see lily
....lily amanda
hi steven
lily amanda
you will see lily amanda

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值