Introduction to Perl Basic Grammar

Time:2019-10-6

I. Data Types(Data type)

The data type of Perl can be roughly divided into four kinds: Scalar (variable), Scalar Array (array), Hash Array (hash), References (pointer), which looks less but uses more than enough. Especially when writing Perl programs, it is very convenient for people who have just learnt the programming language to declare variables in advance. However, for the convenience of program debugging and maintenance in the future, I suggest you develop the habit of declaring variables in advance.

1 Scalar(Pure variables):

Pure variable is the most basic data type in Perl. It can represent a character, string, integer, or even floating point number. Perl sees them all as the same thing. You can even mix them up, amazing. For example:
# There are notes at the beginning and at the end of the well.
# Pure variables begin with $
# My is a way of declaring variables. It regionalizes variables.
# If you declare a variable without adding my or local, Perl uses it as a global variable.
# Traditionally, we enclose strings in double quotation marks, while numeric values do not need to be quoted.
my $x=”abc”;
my $x=123;
my $x=4.56;

1-1 Common Operator

1) Arithmetic operators
+ (addition), -(subtraction), * (multiplication), /(division), ** (power), (remainder), -(negative)
(1) The result of power (**) cannot exceed the range of numbers. When the exponent is decimal, the base number cannot be negative, for example: 25** 1.5 = 125, (-25)** 1.5=? (not established)
(2) The remainder (%) operand is an integer, otherwise it should be intercepted. The second number cannot be zero (because the divisor cannot be zero)
(3) Negative (-) – $a= $a*(-1)
In addition, note that when a string participates in an operation and needs to be converted to an integer, if it cannot be converted to an integer, the value is 0. For example:’2’+1=3,’a’+1=1

2) Number comparison operator
<(less than),=(equal),>(greater),==(equal),<=(less than equal),>=(greater than equal),<=(less than equal),>=(greater than equal),!=(not equal),<=>(comparison)
(1) ==: Comparing operation, the result of comparison is true or non-zero, false or zero.
(2) <=>: Comparisons such as: $a <=> $b, when $a > $b, the value is 1; when $a < $b, the value is – 1; and when $a == $b, the value is 0.
(3) Automatically convert operands into integers, but 0 if integers cannot be converted into integers.
(4) Floating-point numbers are not accurate. Do not compare numbers with similar values, otherwise the results are unexpected.

3) String comparison operator
Lt (less than), GT (greater than), EQ (equal to), Le (less than equal to), Ge (greater than equal to), ne (equal to), CMP (comparison)
(1) Principles of string comparison: Comparing numbers in alphabetical order, numbers < capital letters < lowercase letters (a small-z big)
(2) The order of string comparison: string comparison from left to right. ‘a Z z'<‘b C’ (i.e., first compare a with b, then compare Z with c)
(3) When one string is another prefix, the length is large. For example: dog < doghouse
(4) Strings can be carried from right to left and are alphanumeric
(5) Automatically convert operands into strings. 123 LT 45 =>’123’LT’45’
(6) CMP is equal to <=>, the result is -1,0,1
For example: $str1=”a”, $str2=”a”, then print ($str1 CMP $str2) ==> 0
For example: $str1=”a”, $str2=”b”, then print ($str1 CMP $str2)===>-1
For example: $str1=”b”, $str2=”a”, then print ($str1 CMP $str2)===> 1
(7) Empty string, 0, Undef, all three cases are false.
For example, the results of the following comparisons
35!= 30 + 5 False
35 = 35.0 True
’35’EQ’35.0′ false (compared as a string)
‘fred’lt’barney’ false
‘fred’lt’free’ false
‘fred’eq’fred’ true
‘fred’EQ “Fred” False
”gt”True

4), String Connection (.), Character/String Repetition (x)
(1) Connection (“.”), e.g. $a=’a’.’b’; =>’ab’
Print $a$b=>print $a.$b can be written directly when print is used; however, the two principles are different.
(2) Repetition (“x”), note: there are spaces before and after (purpose: to separate the variable name), such as:’a’x 5=’aaaaa’, if the number of repetitions < 1, return to the empty string.
For example, “5” x 4, that is, “5555”
For example, “love” x (4 + 1) means “love love love love love”
For example, “4.8” x 4 is “4.84.84.8”.
For example: 6.1 x 3, that is: “6.16.16.1”
Namely: the left side is a string, and the right side is the number of occurrences of the string.

5), logical operators (& (and) (and), | | (or) (or),! (not) (non), XOR (exclusive or)
(1) Calculate the value on the left first, then the value on the right.
(2) & & and have different priorities, but it’s difficult to distinguish between them unless special circumstances arise.

6), Bit Operator
& (bitwise and), | (bitwise or), ~ (bitwise non), ^ (bitwise exclusive or), < < (left shift), > (right shift)
(1) The operand is a binary integer, and if it is a decimal, it is intercepted as an integer.
(2)
(3) > move to the right, the first complement is 0, the value is half of the original value (and take the whole) (for example: z > 4, then z = z/(the power of 2))

7), assignment operator
=、+=、-=、*=、/=、%=、**=、&=、|=、^=、.=
(1)$a+=1=>$a=$a+1
(2) Can be connected to $a=$b=3; =>$a=3; $b=3;
(3) Mixed ($a= $b) += 3; => $a= $b; $a= $a + 3; (not recommended)

8), self-increasing (++), self-decreasing (–)
(1) Do not use this operator on either side of the variable: ++$var–
(2) Do not use variables in the same expression after they increase or decrease: $var2 = $var1 + +$var1;
(3) Can be used for string self-increment, when z, Z, 9 carry. $a=’caz’; $a++; ==> $a=’cba’;
(4) Can not be used for string self-subtraction, when $a -, according to the number of operations, the character first converted to zero and then self-subtraction.
(5) If the string contains non-alphanumeric symbols, or if the number is in the letter, the auto-increment is first reduced to zero and then auto-increment.
For example, $a=’ab*c’, $a++, ==> $a = 1;
For example, $a=’ab5c’, $a++, ==> $a = 1;
(6) Pre-increment of $b=+$a, $a increases first and then assigns, then increases $b=$a+; $a assigns first and then increases itself; conversely, the same is true.
For example, $a = 1, $b=+$a, => a = 2, $b = 2;
For example, $a = 1, $b = $a ++, => a = 2, $b = 1;
(7) It can only be used for a single variable, not for a variable after operation. For example: ($a+$b)++.

9), comma (equivalent to: write two statements in one line)
Scope of application: Use only when two statements are closely related
For example: $a+= 1, $b= $a; => $a+= 1; $b= $a;
For example: $a= “ab5c”, print $a. ” n”;

10. Conditional Operator
Conditions? True: false
(1) Three operands: first, the operation on the conditional expression is performed when it is true: the operation on the left side, and the operation on the right side when it is false.
For example: $result = $var = 0? 14: 7;
(2) For simple conditions
(3) Conditional expressions are used on the left side of =
For example: $condvar = 43? $var1: $var2 = 14;
For example: $condvar = 43? $var1 = 14: $var2 = 14;

3. Operator precedence — priority
When several different operators appear in an expression, which is calculated first and which is calculated later
For example: $condvar = 43? $var1: $var2 = 14; (preconditions before assignments)
For example: $x = $a = $b; (calculates relations first, then assignments)
For example: $x = 0 | | Y / $x > 5; (divide first, then greater, then equal, finally relationship or)
For example: $result = 11 * 2 + 6 ** 2 < < 2; (first calculate power, then multiply, then add, then move left, and finally assign value)
(1) The general priorities are as follows: self-increasing and self-decreasing are the highest, single operand is higher than multi-operand, number operation > comparison operation (number comparison and string comparison) > bit operation > assignment operation > logic operation.
(2) Numeric operations: power >*/>+.
(3) Comparisons: <(less), >(greater) higher than (== and!=)

2 Scalar Array
The concept of Perl array variables and lists. Lists are values of a sequence contained in parentheses. They can be any number or empty. Lists are stored in Perl array variables. Unlike simple variables, Perl array variables begin with the character “@”.

Perl Array Variables and Lists

First, list

A list is a sequence of values contained in parentheses, which can be either null or null, such as:

(1,5.3, “hello”, 2), empty list: ().

Note: A list containing only one value (e.g. (43.2)) is different from the value itself (i.e. 43.2), but they can

To transform or assign values to each other.

List of examples:

(17,$var,”astring”)

(17,26<<2)

(17,$var1+$var2)

($value,”Theansweris$value”)

Perl Array–Storage of Lists

Lists are stored in Perl array variables. Unlike simple variables, Perl array variables begin with a character “@”, such as:

@array=(1,2,3);

Note:

(1) When a Perl array variable is created, the initial value is an empty list: ().

(2) Because PERL uses @ and $to distinguish between Perl array variables and simple variables, the same name can be used for Perl at the same time.

Array variables and simple variables, such as:

$var=1;

@var=(11,27.1,”astring”);

But this is easy to confuse, so it is not recommended.

1. Access to Perl arrays

Values in Perl arrays are accessed by subscripts, with the first element subscribed to 0. Attempt to access non-existent Perl arrays

The result is NULL, but if you assign values to elements beyond the size of Perl arrays, the Perl arrays grow automatically.

No element value is NULL. Such as:

@array=(1,2,3,4);

$scalar=$array[0];

$array[3]=5;#[email protected](1,2,3,5)

$scalar=$array[4];#now$scalar=null;

$array[6]=17;#[email protected](1,2,3,5,””,””,17)

_Perl Array Copies

@[email protected];

Apply Perl arrays to lists

@list1=(2,3,4);

@list2=(1,@list1,5);#@list2=(1,2,3,4,5)

Apportionment of_Perl Arrays to Simple Variables

(1)@array=(5,7,11);

($var1, $var2) [email protected]; #$VAR1 = 5, $var2 = 7,11 is ignored

(2)@array=(5,7);

($var1,$var2,$var3)[email protected];#$var1=5,$var2=7,$var3=””(null)

Assignment of variables from standard input (STDIN)

$var=<STDIN>;

@ array = < STDIN >; # ^ D is the sign to end the input

2. Square brackets and variable substitution in strings

“$var [0]” is the first element of the Perl array @var.

“$var[0]” escapes the character “[” equivalent to “$var”. “[0]”, where $var is replaced by a variable, and [0] remains unchanged.

“${var} [0]” is also equivalent to “$var”. “[0]”.

“${var}” cancels the bracketed variable substitution function and contains the text: ${var}.

3. List scope:

(1..10)=(1,2,3,4,5,6,7,8,9,10)

(2,5..7,11)=(2,5,6,7,11)

(3..3)=(3)

For Real Numbers

(2.1..5.3)=(2.1,3.1,4.1,5.1)

(4.5..1.6)=()

For strings

(“aaa”..”aad”)=(“aaa”,”aab”,”aac”,”aad”)

@day_of_month=(“01”..”31″)

_may contain variables or expressions

($var1..$var2+5)

Tips:

$fred=”Fred”;

print((“Hello,”.$fred.”!\n”)x2);

The results are as follows:

Hello,Fred!

Hello,Fred!

4. Output of Perl array:

(1)@array=(1,2,3);

print(@array,”\n”);

The result is:

123

(2)@array=(1,2,3);

print(“@array\n”);

The result is:

123

5. Length of List/Perl Array

When the Perl array variable appears where the expected simple variable appears, the PERL interpreter takes its length.

@array=(1,2,3);

[email protected];#scalar=3, that is, the length of @array

($scalar) [email protected]; #$scalar = 1, the value of the first element of @array

Note: Perl array length as the number of cycles can be programmed as follows:

$count=1;

while($count<[email protected]){

print(“element$count:$array[$count-1]\n”);

$count++;

}

6. SubPerl Array

@array=(1,2,3,4,5);

@[email protected][0,1];#@subarray=(1,2)

@[email protected][1..3];#@subarray2=(2,3,4)

@array[0,1]=(“string”,46);#@array=(“string”,46,3,4,5)now

@array[0..3]=(11,22,33,44);#@array=(11,22,33,44,5)now

@array[1,2,3][email protected][3,2,4];#@array=(11,44,33,5,5)now

@array[0..2][email protected][3,4];#@array=(5,5,””,5,5)now

Elements can be exchanged in the form of subPerl arrays:

@array[1,2][email protected][2,1];

7. Library functions for Perl arrays

(1) sort — sort in character order

@array=(“this”,”is”,”a”,”test”);

@array2=sort(@array);#@array2=(“a”,”is”,”test”,”this”)

@array=(70,100,8);

@array=sort(@array);#@array=(100,70,8)now

(2) Reverse — Reverse Perl arrays

@array2=reverse(@array);

@array2=reversesort(@array);

(3) Chop-Perl array tailing

The meaning of chop is to remove the newline character, the last character when STDIN (keyboard) enters a string. If it works on Perl arrays, it does this for every element in Perl arrays.

@list=(“rabbit”,”12345″,”quartz”);

chop(@list);#@list=(“rabbi”,”1234″,”quart”)now

(4) join/split — join/split

The first parameter of a join is the intermediate character used for the join, and the rest is the Perl array of characters to be joined.

$string = join (“,” “this,” “is,” “a,” “string”); The result is “thisisastring”

@list=(“words”,”and”);

String = join (“:”, @list, @colons”); and # results in”words:: and:: colons”

@array=split(/::/,$string);#@array=(“words”,”and”,”colons”)now

3 Hash Array(Associative Array)
Common usage of Perl hash
Basic Usage
# Initialization% h is an empty array% H = {}; # Initialization% h with an array is a = > 1, B = > 2% H = (‘a’, 1,’b’, 2); # is just another more visualized way of writing. % H = (‘a’= > 1,’b’= > 2); # If the key is a string, quotation marks can be omitted. The following line is the same as the previous line in% H = (a=> 1, b=> 2); Access print with {}; $h {a}\ n; Print 1 $h {b}= `2b’; Print $h {b} Delete key with deletedelete $h {b}; \ Delete’b’from $h.
Empty hash
undef %h

Get all the key values of hash
# To get all keys, the order depends on the hash function, or the disorder.
@all_keys = keys %h;
# All key values are arranged from large to small according to hash values. Value comparisons are digital comparisons (for example, 10 > 9)
@all_keys = sort{$h{$b}<=>$h{$a}} (keys %h);
# All key values are arranged from small to large according to hash values. Value comparison is digital comparison
@all_keys = sort{$h{$a}<=>$h{$b}} (keys %h);
# All key values are arranged from small to large according to hash values. Value comparisons are string comparisons (for example,’10′<‘9’)
@all_keys = sort{$h{$a} cmp $h{$b}} (keys %h);

Determine whether hash contains key
exists($h{$key});

Length of Hash
Want to know how much data a hash holds
$hash_size = keys %h
# Put the length of% h in $hash_size
print scalar kes %h, “\n”
# Print% h length. Scalar is used here to return the length of the array.

Traversing a hash
while (my ($k, $v) = each %h) {print “$k —> $v\n”;}

Reference reference
Reference is similar to C/C++ pointer
$h_ref = \%h;
# Get a hash reference% aHash =%{$h_ref};
# Think of hash reference as hash with $value = $h_ref->{akey}
# This is the same as% h {akey}

Transfer hash to function
Usually it passes a reference to a function.

%h = ();$h{a}=1;foo(\%h)print $h{b}, “\n”;
# Print out 2.
This value comes from the function foo () sub foo {my ($h) = @; print $h – > {a}, “_ n”;
# Print out $1 H – > {b} = 2;}

Function returns hash, or hash reference
Functions can return hash
sub foo {my %fh;$fh{a} = 1;return %h;} my %h = foo();print

Two control structure(Control Statements)
1 Choice ifstructure
Perl’s conditional control narrative is similar to C language, allowing users to quickly master it. But Perl has more practical grammar than C. I’ll mark it with the bottom line, you can see at a glance.

# Expression is a conditional narrative. Like C, Perl does not define Boolean data type.
# So zero is false and non-zero is ture. In addition, it should be noted that string operators and numerical operators should be clearly distinguished.
# Code Segment is a set of instructions enclosed in braces, which is a Block.
if (Expression) {Code Segment}
if (Expression) {Code Segment} else {Code Segment}
if (Expression) {Code Segment} elsif (Expression) {Code Segment} else {CodeSegment}
# elsif is else if
# If there is only one statement, we can use inverted syntax, which looks more concise.
statement if (Expression);
# unless is if not
Statement unless (expression);
print “HELLO!\n” if ($name eq “friend”);
$x-=10 if ($x == 100);
Look! There are some Perls in C, most of them. People who have studied C can learn Perl effortlessly.

2Cyclic structure
Perl’s circular control narrative is also very similar to C, of course, Perl also has some more practical grammar as an example:
# Note: A dollar sign should be added before a pure variable, which is different from C.
for($i=0; $i<=10; $i++) {Code Segment}

# Foreach is inherited from UNIX shell script.
# The first independent variable is a pure variable. The second independent variable is enclosed in parentheses. It contains an array of pure variables.
# As the name implies, it passes each element of an array in sequence to the first independent variable until all are passed.
# It differs from for ($i = 0; $i <=$# array; $i++), but the purpose is to extract each element of the array.
foreach $i (@array) {Code Segment}
# In fact, in Perl, for and foreach can be used together, depending on the habits of the people.
# The following line is the same as the first one above, but it’s much simpler. You can try it.
for $i (0..10) {Code Segment}

# While controls loops and post-loops.
while($i<=10) {Code Segment}
do {Code Segment} while(Expression);
# Perl also has the same instructions as break and continue in C, which Perl calls last and next.
# Last is the loop in which the jump occurs, and next is the next loop that executes directly by skipping the following instructions.
while(chomp($i=)) {
next if ($i == 5);
last unless ($i > 10);
}

Perl also provides the grammar of label, the goto directive, but experienced programers don’t like it, and I don’t recommend it, so press it. Interested persons please refer to it by yourselves. It’s also worth noting that Perl doesn’t provide a switch narrative like C, but Perl’s pattern matching is very powerful, so I suggest you use if else narrative directly.

3subroutine(Subroutines)
(a) Syntax: sub NAME {Code}
(b) Call subroutine: & NAME (para1, para2,…)
(c) Parameter transfer:@_
Perl and C adopt Call by value, but because Perl does not declare variables in advance, it is not necessary to declare what parameters to pass when building subroutines. When the main program passes parameters to the subroutine, Perl places the parameters enclosed in brackets in a special global variable @ array in order. Then the subroutine can freely use the parameters in @ array, such as $[0] is the first parameter, $[1] is the second parameter, or use my ($a1, $a2, $a3,…) = @; to extract the parameters, of course my @arg= @ or my% arg= @; It’s also possible. Because Perl’s grammar is very lively, it makes the maintenance of the program particularly difficult, so writing annotations becomes an important task. I suggest that you should add a description of this subroutine before each subroutine, especially the parameters that need to be passed clearly.
(d) Variable Localization:my or local
Usually the variables we define in the program are global variables, so if we want to regionalize the variables in the subroutine, we need to add my or local keywords, such as my $x = 3; if the name of the variables used in the subroutine is careless and the main process is the same, Perl will take the variables in the subroutine currently being executed as the priority.

4 I/OAnd file processing
(a) Syntax:
open(FILEHANDLE,”Expression”);
close(FILEHANDLE);
The expression here is a description with the name of the file, and if the expression only has the name of the file without the description, it is presupposed to be read-only. Expressions are described as follows:

Expression    Effect
open(FH, ” filename”)
open(FH, “+filename”)
open(FH, “>filename”)      Opens filename for writing.
open(FH, “+>filename”)    Opens filename for both reading and writing.
open(FH, “>>filename”)    Appends to filename.
open(FH, “command|”)     Runs the command and pipes its output to thefilehandle.
open(FH, “command|”)     Pipes the output along the filehandle to thecommand.
open(FH, “-“)     Opens STDIN.
open(FH, “>-“)     Opens STDOUT.
open(FH, “<&=N”) Where N is a number, this performs the equivalent of C’sfdopen for reading.
open(FH, “>&=N”)  Where N is a number, this performs the equivalent of C’sfdopen for writing.
Example:
# Open the file $filename, print the message behind die if it fails to open, and end the program.
open(FILE, $filename) || die “Can’t open file $filename : $!\n”;

# The following is a very concise way of writing, which is equivalent to while ($=) {print “$”;).
print while();

# It’s a good habit to write programs when you open files and close them at will.
close(FILE);

# Both $! And $_are special variables of Perl, as described below.

(b) Input:
Perl has no special function for input, because when Perl executes a program, it automatically opens the standard input device and its file handle is STDIN, so the method to input data in Perl is to use:

# Perl does not automatically remove the C R/LF at the end, unlike C, so use the chomp function to help you remove it.
# People often forget this action, resulting in different results than you think, we should pay special attention to it.
$input=<STDIN>; chomp $input;
# The following is a more concise way of writing.
chomp($input=<STDIN>);

(c) Output: print “variables or strings”;
Perl also has printf () function. Syntax is exactly the same as C, so I do not introduce much. Perl also has a print function, which is more convenient and useful than printf (), so you can’t help it. Output is nothing more than output to the screen or file. It is easy to understand with examples.

# It’s no longer necessary to specify the data type of the variable. Isn’t that more convenient than printf ()?
print “Scalar value is $x\n”;

# It is an operator of string addition. The upper and lower lines are equivalent.
print “Scalar value is ” . $x . “\n”;

# Method of exporting to a file.
print FILE “print $x to a file.”;

# Here’s a special use of print. Learn how to use shell script.
print<XXX

This is called here document. XXX can be any identifier you take. The words between the identifiers will be output as you write, just like the tag. When a line begins with the identifier you fetch from XXX, the output stops.
XXX

Perl also has special characters beginning with “” like C:
\t    tab
\n    newline
\r    return
\f    form feed
\b    backspace
\a    alarm(bell)
\e    escape
\033  octalchar
\x1b  hex char
\c[   control char
\l    lowercase next char
\u    uppercase next char
\L    lowercase till \E
\U    uppercase till \E
\E    end case modification
\Q    quoteregexp metacharacters till \E

It should also be noted that Perl incorporates the usage conventions of UNIX shell script. Strings enclosed in double quotes (“”) are expanded first, but the characters behind backslashes () are not expanded and treated as general characters. Strings enclosed by single quotation marks (”) will not expand at all. Strings enclosed by anti-single quotation marks (“) will execute it as command-line instructions, equal to system (). Beginners often get confused, but after getting used to it, they will feel that they can’t distinguish it so clearly. Let’s give an example.
$x=”ls -l”;
print “$x”;             # Output ls -l
print “\$x”;            # Output $x
print ‘$x’;             # Output $x
print `$x`;             # Output files in this directory

function
1. Perl function
Through & Call.

2. Perl parameters
Perl naturally supports variable numbers of parameters.
Inside a function, all parameters are placed in an array @ in order. Inside a function, $[0] represents the first of the functions.

Parameters, other analogies.

3. shift
Shift is followed by an array to indicate that the first value of the array is returned. The array is also changed, and its first element is bombed.

Out.

Demo Code 1 (Maximum):
#!/usr/bin/perl -w
use strict;
# Call the function max, get the maximum value of a set of values, and output.
my $maxCnt = &max(11,22,33);
print “maxCnt=$maxCnt\n”;

sub max {
# The traversal algorithm is adopted. First assign the first value of the parameter to $current MaxCnt.
#@ It is the default array that contains all the parameters of the function, such as (11, 22, 33).
# Shift @ has two results: 1. The first value in the array @ is assigned as the return value.

CurrtMaxCnt). 2. Pop up the first value of the @ array [and then change the value of @ to (22,33)].
my $currentMaxCnt = shift @_;
# When shift is used in functions, @_can be omitted. The above code can also be written in this way.
#  my $currentMaxCnt = shift;

# Traverse the entire @_array.
foreach ( @_ ) {
# The $_represents the element currently traversed in the array @.
if ( $_ > $currentMaxCnt ) {
# If you find that the current array element is larger than $current MaxCnt, reassign $current MaxCnt to the current one

Element.
$currentMaxCnt = $_;
}
}
# The return value of the function is the scalar $current MaxCnt.
return $currentMaxCnt;
}

Demonstration code 2 (summation):
#!/usr/bin/perl -w
use strict;

# Find the sum of a set of numbers and print them.
my $s1 = &sumvar(11,22,33);
my $s2 = &sumarg(22,33,44);
my $s3 = &sumgod(11,22,33,44,55);
print “s1=$s1, s2=$s2, s3=$s3\n”;

Method 1
sub sumvar {
# Assign the first three element values of the parameter array to ($first, $second, $third)
(my $first, my $second, my $third) = @_;
# Returns its sum value. Disadvantage: If the sum of four parameters is obtained, only the sum of the first three parameters can be given.
return $first + $second + $third;
}

Method 2
sub sumarg {
# The $[0] represents the first element of the parameter array @. Other analogies.
my $first = $_[0];
my $second = $_[1];
my $third = $_[2];
# Returns its sum value. Disadvantage: Similar to sumvar. Just learn the usage of $[0] here.
return $first + $second + $third;
}

# Method 3, parameters can be arbitrary. We can all find the sum.
sub sumgod{
my $s = shift @_;
foreach ( @_ ) {
$s = $s + $_;
}
# Like the previous function max.
return $s;
}

8summary
I have sorted out some symbols, usages, functions, libraries and so on that I think I use more. These are very basic.

Yes, but it will be helpful to improve efficiency.

Data manipulation
* $- Declare and reference variables with a scalar
*@- Declare and reference a list, but when accessing a list member, use $ListName [index]
*%- Declare and reference a hash table, but when accessing a hash member, you need to use $HashName

{key}

Special variable
* $0 – File name of the current running script
*@ ARGV – A list of command line parameters for the current running script
* $- Default variables, such as the current variable in the loop
*@- List of input parameters for functions
*% ENV – Environmental Variables of the System
*@ INC – Perl’s Include Path List, which we can add our own directory to for easy reference

Using custom Libraries
* $! – Current system prompt, error message
* $^O – the name of the operating system.
* STDIN, STDOUT, STDERR – Default handle for input and output, which can be customized to some extent
*=>- When declaring a hash, it can be used to explicitly express the corresponding relationship between key=> value
* $^ I – Specify the suffix name of the backup file, so that the modified file will automatically save a side with that suffix name

book

Special Usage
*& Sub – Calls a function, although Perl has rules that allow you to omit the & symbol here at some point, but

Considering consistency, I always use this method to call custom functions.
* $ is used to get the maximum index of an array of modules, and in general, the last element can be represented by -1.

Index.
* QW () – Quickly declare an array of strings, eliminating annoying Quotes

regular expression
* $- Gets the matches captured in parentheses
* $`, $&, $’- Get the matching string and its front and back parts
*^ The beginning and end position of the $- string, used for positioning

Common functions
* Operating functions of pop, push, shift, unshift, reverse – List
* Operating functions of keys, values, exists, each, delete – hash
* Chomp, split, join, index, substr, sort – string operation functions
* Sprintf, printf, print – formatted output function
* system, exec, `system command call function
* glob, unlink, mkdir, rmdir, rename,chmod,chown, open, close, opendir,

Cloedir – File System Operating Function
* stat, lstat, localtime, gmtime, utime – Document properties, time-related functions
* Hex, OCT – binary, octal, hexadecimal number into decimal function
* Grep, map – list advanced operation functions

Detailed descriptions of these functions can be obtained by command:
#perldoc -f functionname
find out

Common library
* File:: Basename – Get file name or file path based on path
* File:: Spec – Combines file names and paths to form a full path
* File:: Find – recursively traverses all files in a directory
* XML:: Simple – Expressing XML files in a complex structure is quite convenient to use.
* Time:: HiRes – often used to calculate the time spent on an operation
* Getopt:: Long – Used when scripts require complex input parameters and options
* Cwd – Get the current working directory
* IO:: File – File operations
* Win32 – I use it when I need to call some Windows APIs

Recommended Today

Introduction and overview of NoSQL

1.1 INTRODUCTION1.1.1 1 under the background of Internet era, why do you use nosql1 single machine MySQL In the 1990s, the number of visitors to a website was generally small, and it could be easily handled with a single database. At that time, there were more static web pages and less dynamic interactive websites. Under […]