Perl中的特殊变量

Perl中的特殊变量


1. $&, $`,$' 用在模式匹配中


$&  用来存放匹配中的值
$`   用来存放匹配中之前所有字符
$
'   用来存放匹配中之后所有字符

如:
#!/usr/bin/perl -w
if("Hello good  there,neigbor hello" =~ /S(w+),/)
{
        
print "That actually matched '$&'. ";
        
print $`." ";
        
print $'." ";
}

执行的结果为:

That actually matched 
'there,'.
Hello good  
neigbor hello

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

另外常用的变量@_
@_是子程序的一个私有变量◆;如果有一个全局变量@_,它将在此子程序调用前存储起来,当子程序调用完成后,其早期的值会被重新赋还给@_◆。这意味着当将参数传递给子程序时不用担心它会影响此程序中其它子程序的@_这个变量的值。嵌套的子程序调用时,@_的值和上述类似。甚至此子程序递归调用时,每一次调用将得到新的@_,因此子程序调用时将得到其自身的参数列表。

◆除非调用的子程序前有&而后面没有括号(或者没有参数),此时@_从此调用者的上下文(context)得到。这通常不是个好主意,但有时很
有用。


2. Perl - $_ and @_


Perl's a great language for special variables - variables that are set up without the programmer having to intervene and providing information ranging from the number of lines read from the current input file ($.) through the current process ID ($$) and the operating system ($^O). Other special variables effect how certain operations are performed ($| controlling output buffering / flushing, for example), or are fundamental in the operation of certain facilities - no more so than $_ and @_.

Lets clear a misconception. 
$_  and  @_  are  different variables . In Perl, you can have a list and a scalar of the same name, and they refer to unrelated pieces of memory.

$_ is known as the "default input and pattern matching space".  In other words, if you read in from a file handle at the top of a  while  loop, or run a  foreach  loop and don't name a loop variable, $_ is set up for you. Then any regular expression matches,  chop s (and  lc s and many more) without a parameter, and even  print s assume you want to work on $_. Thus:
while ($line = <FH>) {
  if ($line =~ /Perl/) {
    print FHO $line;
    }
  print uc $line;
  }


Shortens to:
while (<FH>) {
  /Perl/ and
    print FHO ;
  print uc;
  }


@_ 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 $PID for $$. But  use English;  can have a detrimental performance effect if you're matching regular expressions against long incoming strings. 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值