xywuyiba7 发表于 2015-12-25 15:10:55

Perl中的特殊符号

$_   
  俗称perl的老地方,当你的程序中未告知使用哪个参数或者变量时,perl就会自动使用$_中的值,比如



for(1..10){
    print ;
}
  这里print没有指定参数,所以它就会使用$_,那$_里面是什么呢?每次循环$_的值都会变化,所以$_实际上就是1 .. 10这10个值,所以上面的代码打印的结果就是12345678910

$!
  当且仅当某个函数调用失败时才会设置该变量,所以经常这样使用这个变量



open FILE,"<d:/code/zdd.txt" or die $! ;
$/
  这是perl中的行分隔符,默认是换行符,可以改变这个变量以便一次读入整个文件,如下



sub test{
    open FILE,"<d:/code/zdd.txt" or die $! ;
    my$olds= $/ ;
    local $/=undef ;
    my$slurp=<FILE> ;
    print$slurp,"\n" ;
    $/=$olds ;
}
$`   
  正则表达式匹配变量,代表匹配位置之前的内容

$&   
  正则表达式匹配变量,代表匹配的内容

$'   
  正则表达式匹配变量,代表匹配位置之后的内容
  来看一个例子,解析xml文件,有如下xml文件,我想获得Code节点的值



<?xml version='1.0' encoding='UTF-8'?>
<Code>200</Code>

  用下面的perl代码来解析



my$str="<Code>200</Code>" ;
if($str=~/(?<=<Code>)(\d+)(?=<\/Code>)/){
    print"string before matched: $`","\n" ;
    print"matched string: $&","\n" ;
    print"string after matched: $'","\n" ;
}
  运行结果是
  string before matched: <Code>
matched string: 200
string after matched: </Code>
  其中$`对应<Code>,$&对应200,$'对应</Code>

$|
  控制对当前选择的输出文件句柄的缓冲,例子待添加。

@_
  传给子程序的参数列表,通常一个子程序是这样获得传给它的参数的。



sub add {
    my ($num1, $num2) = @_;
    return $num1 + $num2;
}
  如果子程序只有一个参数,也可以用shift来获取,此时,shift相当于shift @_



sub square {
    my $num = shift ; # same as my $num = shift @_
    return $num * $num;
}
  
  ==
页: [1]
查看完整版本: Perl中的特殊符号