Introduction to special symbols in Perl

Time:2021-11-7

$_  

In the old place commonly known as Perl, Perl will be used automatically when your program is not told which parameter or variable to use$_ Values in, such as

?
1
2
3
for(1..10){
  print ;
}

Here print does not specify parameters, so it uses $_, That$_ What’s inside? Each cycle$_ The value of will change, so$_ In fact, it is the 10 values of 1.. 10, so the print result of the above code is 12345678910

$!

This variable is set when and only when a function call fails, so it is often used in this way

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

$/

This is the line separator in Perl. The default is line feed. You can change this variable to read the entire file at one time, 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 expressions match variables, representing the contents before the matching position

$&  

Regular expressions match variables, representing the matching content

$' 

Regular expressions match variables, representing the contents after the matching position

Let’s take an example to parse the XML file. There are the following XML files. 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 is

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

Where $` corresponds to < code >, $& corresponds to 200, and $’corresponds to < / code >

$|

Controls the buffering of the currently selected output file handle. Examples to be added.

@_

A list of parameters passed to a subroutine. Usually, a subroutine obtains the parameters passed to it in this way.

?
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 obtain it. At this time, shift is equivalent to [email protected]_

?
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 and right value

->Reference, which is equivalent to the point number in [object. Method name] in Java

: represents a method of the calling class

%Hash flag that defines the type of a key value pair

@Flag of array

Flag for $scalar

=~Matching flags

!~ Mismatched flags

$! Returns the error number or error string according to the context