您的位置:首页 > 其它

Perl中的特殊变量

2009-01-06 15:16 211 查看

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, chops (and lcs and many more) without a parameter, and even prints 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. 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: