Introduction to Special Symbols in Perl

Commonly known as the old place of perl, when you do not tell which parameter or variable to use in your program, perl will automatically use the value in $_, such as

1

2

3

for(1..10){

  print ;

}

Here print does not specify parameters, so it will use $_, so what is in $_? The value of $_ will change every time the loop, so $_ is actually 1 .. 10 these 10 values, so the result printed by the above code is 12345678910

$!

This variable will be set if and only if a function call fails, so this variable is often used like this

open FILE,"<d:/code/zdd.txt" or die $! ;

$/

This is the line separator in perl, the default is a newline, you can change this variable to read the entire file at once, as follows

1

2

3

4

5

6

7

8

sub test{

  open FILE,"<d:/code/zdd.txt" or die $! ;

  my$olds= $/ ;

  local $/=undef ;

  my$slurp=<FILE> ;

  print$slurp,"\n" ;

  $/=$olds ;

}

$`

Regular expression matching variable, representing the content before the matching position

$&  

Regular expression matching variable, representing the matched content

$' 

Regular expression matching variable, representing the content after the matching position

Let's look at an example, parse the xml file, there is the following xml file, I want to get the value of the Code node

<?xml version='1.0' encoding='UTF-8'?>
<Code>200</Code>
Use the following perl code to parse

1

2

3

4

5

6

my$str="<Code>200</Code>" ;

if($str=~/(?<=<Code>)(\d+)(?=<\/Code>)/){

  print"string before matched: $`","\n" ;

  print"matched string: $&","\n" ;

  print"string after matched: $'","\n" ;

}

The result of the operation is

string before matched: <Code>
matched string: 200
string after matched: </Code>

Among them, $` corresponds to <Code>, $& corresponds to 200, $' corresponds to </Code>

$|

Control the buffering of the currently selected output file handle, examples are to be added.

@_

The list of parameters passed to the subroutine, usually this is how a subroutine obtains the parameters passed to it.

1

2

3

4

sub add {

  my ($num1, $num2) = @_;

  return $num1 + $num2;

}

If the subroutine has only one parameter, you can also use shift to get it. At this time, shift is equivalent to shift @_

1

2

3

4

sub square {

  my $num = shift ; # same as my $num = shift @_

  return $num * $num;

}

perl common symbols

=> key-value pair, left key right value

-> Reference, equivalent to the dot in [object. method name] in java

:: 表示调用类的一个方法

% 散列的标志,定义一个键值对类型的

@ 数组的标志

$ 标量的标志

=~ 匹配的标志

!~ 不匹配的标志

$! 根据上下文返回错误号或者错误串

Guess you like

Origin blog.csdn.net/jh035/article/details/128141597