perl教程-子程序

来源:互联网 发布:网络小贷牌照用途 编辑:程序博客网 时间:2024/06/06 02:28

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

点击打开链接

点击打开链接


@_ 在某个函数内,数组 @_ 包含传递给该函数的所有参数。   在标量的上下文之中是指,数组元素的个数 $_ 默认的输入/输出和格式匹配空间;也即默认省略的控制变量,[akang@akang perl_practice]$ vi call_11.调用的例子1#!/usr/bin/perluse 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

0 0