首页›文章›perl push和pop用法讲解

perl push和pop用法讲解

计算机技术 · perl 程序开发2015-02-121次浏览0 个评论

pop 操作将数组的最后一个元素取出并返回:

perl
@array=5..9;
$fred=pop(@array); #$fred 得到 9,@array 现在为(5,6,7,8)
$barney=pop@array; #$barneygets8,@array 现在为(5,6,7)
pop@array; #@array 现在为(5,6)(7 被丢弃了)

最后一个例子中,pop 使用在"inavoidcontext",也就是说没有存放其返回值的地方。这样使用 pop 是合法的。
如果数组为空,那 pop 什么也不做(因为没有元素可以移出),并返回 undef。
你可能已注意到 pop 后可以使用或者不使用括号。这在 Perl 中是一条通用规则:如果去掉括号含义不变,那括号就是可选的。和 pop 相反的操作是 push,它可以将一个元素(或者一列元素)加在数组的末尾:

perl
push(@array,0); #@array 现在为(5,6,0)
push@array,8; #@array 现在为(5,6,0,8)
push@array,1..10; #@array 现在多了 10 个元素
@others=qw/9 0 2 1 0/;
push@array,@others; #@array 现在又多了 5 个元素(共有 19 个)

push 的第一个参数或者 pop 的唯一参数必须是数组变量。

perl
#!/bin/perl
sub above_average
{
  $number=@_;
  foreach $how(@_)
  {
     $total=$total+$how;
  }
  $the_average=$total/$number;
  foreach (@_)
  {
     if ($_>$the_average)
     {
        push(@larger,$_)#这里不用赋值,数组元素的添加,直接用push就好了
     }
  }
  @larger;#子程序的返回值,一定要有,刚开始没有写
}
print "please input several numbers,and you will get the number which is large than their averagen";
@the_number_input=<STDIN>;
@the_number_larger=above_average(@the_number_input);
print "@the_number_largern";

评论

0

评论加载中…

发表评论

0/2000