perl基础:perl中@_, 和 1,$2,...及其类似变量的含义

由于直接复制的原因,建议阅读原文:http://blog.sciencenet.cn/blog-634847-497909.html.

-------------------------------------------

1.@_含义

1)是perl中默认的数组变量

比如说你想移除数组中的一个元素赋值给一个变   value=shift @abcd;

方法2:你没有定义任何数组
       my $value=shift @_;   和上例等效
       这里perl会隐式的选择@_

2)是sub子函数中的默认参数列表.

例如:
sub funct($$) {
    ($param1, $param2) = @_;
    #Statement
}

再例如,有下面一段代码:
my max_number = &max(1,2);
print "1 and 2 ,the max number is
max_number\n";
sub max{
     my (   num2) = @_[0,1]; ## 取出参数列表中的元素。
     ........此处省略求max运算
}

在子函数中直接shift; 就可以从@_的前端弹出一个元素.

shift;
等于
shift @_;

-------------------------

@_ is the list of incoming parameters to a sub. So if you write a sub, you refer to the first parameter in it as $_[0], the second parameter as $_[1] and so on. And you can refer to $#_ as the index number of the last parameter:
sub demo {
  print "Called with ",#_+1," params\n";
  print "First param was
_[0]\n";

Note that the English module adds in the ability to refer to the special variables by other longer, but easier to remember, names such as @ARG for @_ and   $. But use English; can have a detrimental performance effect if you're matching regular expressions against long incoming strings

2.$_含义

 

1)     _;
2)默认模式匹配空间(pattern matching space)
s/.../.../;
等于
$_ =~ s/.../.../;

---------------------------

Then any regular expression matches, chops (and lcs and many more) without a parameter, and even prints assume you want to work on     line = <FH>) {
  if (   line;
  }

Shortens to:
while (<FH>) {
  /Perl/ and
    print FHO ;
  print uc;
  }
3.   2,...等含义

以数字为名的变量保存的是上一次匹配操作(/pattern/)中,第n个小括号中的原符号所匹配内容。  
  2就是第二对小括号中的原符号所对应的匹配内容。

内插功能:  

  str   =~ /(\d)z{3}(\d)/;  
print   "   2\n";  

输出结果是:4     7  

http://blog.sciencenet.cn/blog-634847-497909.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值