SoFunction
Updated on 2025-04-07

Introduction to special symbols in Perl

$_  

Commonly known as perl, when your program does not tell which parameter or variable to use, perl will automatically use the value in $_, for example

for(1..10){
  print ;
}

Print does not specify parameters here, so it will use $_, so what is inside $_? The value of $_ will change every time the loop, so $_ is actually 1.. 10 and these 10 values, so the above code prints the result 12345678910

$!

This variable is set if and only if the call of a function fails, so this variable is often used in this way.

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

$/

This is the line separator in perl, which is a newline character by default. You can change this variable to read the entire file at once, as follows

sub test{
  open FILE,"<d:/code/" or die $! ;
  my$olds= $/ ;
  local $/=undef ;
  my$slurp=<FILE> ;
  print$slurp,"\n" ;
  $/=$olds ;
}

$`

Regular expression matches variables, representing the content before the matching position

$&  

Regular expression matches variables, representing the matching content

$' 

Regular expression matching variables representing the content after the matching position

Let’s take a look at an example, parsing the xml file, there are 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

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>

where $` corresponds to <Code>, $& corresponds to 200, $' 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 gets the parameters passed to it in this way.

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 @_

sub square {
  my $num = shift ; # same as my $num = shift @_
  return $num * $num;
}

Perl common symbols

=> Key value pair, left and right values

-> Quotation, equivalent to the dot number in [Object. Method Name] in java

:: represents a method that calls the class

% hash flag, defining a key-value pair type

@Array flags

$ scalar flag

=~ Matching flag

!~ Mismatched flag

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