one. Data Type(Data type):
Perl's data types are roughly divided into four types: Scalar (variable), Scalar Array (array), Hash Array (hash), and References (pointers). Although it looks small, it is more than enough to use. Especially when writing Perl programs, you don’t have to declare variables in advance, which is very convenient for those who have just learned programming languages. However, in order to facilitate program error debugging and maintenance in the future, I suggest that you should develop the habit of declaring variables in advance.
1 Scalar(Pure quantitative variable):
Pure quantitative variables are the most basic data type in Perl. They can represent a character, string, integer, or even floating point number, and Perl treats them all as the same thing! You can even mix them up, which is incredible. For example:
# The beginning of the tic-tip is followed by annotations.
# Pure quantitative variables start with $.
# my is a way to declare variables, which can localize variables.
# When declaring a variable, if my or local is not added, Perl will use it as a domain variable.
# We customarily enclose strings in double quotes, and the values do not need to be quoted.
my $x="abc";
my $x=123;
my $x=4.56;
1-1 Commonly used operation operators
1) Arithmetic operators
+(add), -(subtraction), *(multiple), /(division), **(power), %(remain), -(negative)
(1) Exponentiation (**) The result cannot exceed the range of the number. When the exponent is a decimal, the base number cannot be a negative number, for example: 25**1.5=125, (-25)**1.5=? (not established)
(2) Take the remainder (%) operand is an integer, otherwise it must be intercepted. The second number cannot be 0 (because the divisor cannot be 0)
(3) Negative (-) -$a=$a*(-1)
In addition, note that when a string participates in the 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 to), >(greater than), ==(equal to), <=(less than or equal to), >=(greater than or equal to), !=(not equal to), <=>(comparison)
(1) ==: Comparison operation, the result of comparison is true or non-zero, false or zero
(2) <=>: Comparison operation For example: $a<=>$b, when $a>$b, the value is 1; when $a<$b, the value is -1; when $a==$b, the value is 0
(3) Automatically convert operands into integers. If they cannot be converted into integers, they will be 0
(4) Floating point numbers are inaccurate, do not compare numbers with similar values, otherwise the result will be unexpected
3) String comparison operator
lt (less than), gt (greater than), eq (equal to), le (less than or equal to), ge (greater than or equal to), ne (equal to), cmp (comparison)
(1) Comparison principle of strings: Compare in the order of the alphabet, numbers < uppercase letters < lowercase letters (a small - z large)
(2) The order of string comparison: string comparison from left to right. 'azz'<'bc' (i.e., first compare a with b, then z with c)
(3) When one string is the prefix of another, the length of the string is large. For example: dog<doghouse
(4) The string can be carried from right to left, and is made separately by alphanumeric characters
(5) Automatically convert operands into strings. 123 lt 45 => '123' lt '45'
(6) cmp is equivalent to <=>, and 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 following comparison results
35 != 30+5 #Fake
35 == 35.0 #Really
'35' eq '35.0' #Fake (compare as a string)
'fred' lt 'barney' #Fake
'fred' lt 'free' #Fake
'fred' eq "fred" #Really
'fred' eq "Fred" #False
' ' gt ' ' #Really
4) String concatenation (.), Character/String duplication (x)
(1) Connect ( "."), for example: $a='a'.'b'; =>'ab'
You can write print $a$b=>print $a.$b directly when printing; but the principles of these two are different
(2) Repeat ( "x"), note: There are spaces before and after (purpose: to separate from the variable name), for example: ‘a' x 5=’aaaa’, if the number of repetitions is <1, return an empty string
For example: "5" x 4, that is: "5555"
For example: "love" x (4+1), that is: "lovelovelovelovelove"
For example: "4.8" x 4, that is: "4.84.84.84.84.8"
For example: 6.1 x 3, that is: "6.16.16.1"
That is: on the left is a string, on the right is the number of times the string appears
5) Logical operators (&&(and)(and), ||(or)(or), !(not)(non), xor(xor)
(1) Calculate the value on the left first, and then calculate the value on the right.
(2) The priority of && and and is different, but it is difficult to make a difference unless it is special.
6) Bit operation operator
& (bital-wise) , | (bital-wise or), ~ (bital-wise non), ^ (bital-wise XOR), << (left shift), >> (right shift)
(1) The operand is a binary integer. If it is a decimal, it will be intercepted as an integer.
(2) Move << left, after moving it away, the vacancy is 0, the value is 2*N times the original value (for example: z<<4, then z=z* (to the 4th power of 2))
(3) >> Move right, add 0 at the first position, and the value is half of the original value (and round it) (for example: z>>4, then z=z/(to the power of 2))
7) Assignment operator
=、+=、-=、*=、/=、%=、**=、&=、|=、^=、.=
(1)$a+=1=>$a=$a+1
(2) You can wait for $a=$b=3;=>$a=3;$b=3;
(3) Mixed use ($a=$b)+=3;=>$a=$b;$a=$a+3; (not recommended)
8) Self-increase (++), self-decrease (--)
(1) Do not use this operator on both sides of the variable: ++$var--
(2) Do not use it again in the same expression after the variable increases/decrements: $var2 = $var1 + ++$var1;
(3) Can be used for self-increment of strings, and carry when z, Z, and 9. $a='caz'; $a++; ==> $a='cba';
(4) It cannot be used for self-deduction of strings. When $a--, it is calculated by number, and the characters are converted to 0 first and then self-deduction.
(5) If the string contains non-alphanumeric symbols, or the number is in the letter, the self-increase will first be changed to 0 and then self-increase
For example: $a='ab*c'; $a++; ==> $a=1;
For example: $a='ab5c'; $a++; ==> $a=1;
(6) Pre-increase $b=++$a, $a first increases and then assigns value, then increases $b=$a++; $a first assigns value and then increases; otherwise, 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, and the variables after operation cannot be performed. For example: ($a+$b)++
9), comma (equivalent to: write two statements on one line)
Scope of application: Only used 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
condition? true and false
(1) Three operands: First, the conditional expression operation is performed. When it is true, the left operation is performed on: and when it is false, the right operation is performed on: when it is false.
For example: $result = $var == 0 ? 14 : 7;
(2) Used for simple conditions
(3) Conditional expression is used on the left side of =
For example: $condvar == 43 ? $var1 : $var2 = 14;
For example: $condvar == 43 ? $var1 = 14 : $var2 = 14;
3. Operator priority level (precedence--priority)
When several different operators appear in an expression, which one is calculated first and which one is calculated later
For example: $condvar == 43 ? $var1 : $var2 = 14; (calculate the conditions first, then calculate the assignment)
For example: $x = $a == $b; (calculate the relationship first, then calculate the assignment)
For example: $x == 0 || $y / $x > 5; (First calculate division, then calculate greater than, then calculate equal, and finally calculate relationship or)
For example: $result = 11 * 2 + 6 ** 2 << 2; (First calculate the power, then calculate the multiplication, then calculate the addition, then calculate the left shift, and finally calculate the assignment)
(1) The general priority is as follows: self-increase and self-decrease the highest, single operand is higher than multi-operands, number operation > comparison operation (numeric comparison and string comparison) > bit operation > assignment operation > logic operation
(2) Number operation: Power > */>+-
(3) Comparison operation: < (less than), > (greater than) higher than (== and !=)
2 Scalar Array:
The concept of Perl array variables and lists. Lists are values of a sequence contained in brackets. They can be any numerical value or empty. The list is stored in Perl array variables. Unlike simple variables, Perl array variables are first of the character "@".
Perl array variables and lists
1. List
A list is a sequence of values contained in brackets, which can be any numerical value or empty, such as:
(1,5.3,"hello",2), empty list: ().
Note: A list containing only one value (such as: (43.2)) is different from the value itself (ie: 43.2), but they can
To convert or assign values to each other.
List example:
(17,$var,"astring")
(17,26<<2)
(17,$var1+$var2)
($value,"Theansweris$value")
2. Perl array--list storage
Lists are stored in Perl array variables. Unlike simple variables, Perl array variables are first prefixed with the character "@", such as:
@array=(1,2,3);
Note:
(1) The initial value is an empty list when creating Perl array variable: ().
(2) Because PERL uses @ and $ to distinguish Perl array variables from 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
◆The values in the Perl array are accessed through subscripts, and the first element is subscripted to 0. Trying to access non-existent Perl array element
The result is NULL, but if the element exceeds the size of the Perl array is assigned, the Perl array will automatically grow.
The value of the element that has not been present is NULL. like:
@array=(1,2,3,4);
$scalar=$array[0];
$array[3]=5;#now@arrayis(1,2,3,5)
$scalar=$array[4];#now$scalar=null;
$array[6]=17;#now@arrayis(1,2,3,5,"","",17)
◆Copy between Perl arrays
@result=@original;
◆Use Perl array to assign values to list
@list1=(2,3,4);
@list2=(1,@list1,5);#@list2=(1,2,3,4,5)
◆Assignment of Perl array to simple variables
(1)@array=(5,7,11);
($var1,$var2)=@array;#$var1=5,$var2=7,11 is ignored
(2)@array=(5,7);
($var1,$var2,$var3)=@array;#$var1=5,$var2=7,$var3=""(null)
◆ Assign value to variables from standard input (STDIN)
$var=<STDIN>;
@array=<STDIN>;#^D is the symbol of the end input
2. Square brackets and variable replacement in strings
"$var[0]" is the first element of the Perl array @var.
"$var\[0]" escapes the character "[", equivalent to "$var"."[0]", $var is replaced by a variable, and [0] remains unchanged.
"${var}[0]" is also equivalent to "$var"."[0]".
"$\{var}" cancels the variable replacement function of braces, including text: ${var}.
3. List range:
(1..10)=(1,2,3,4,5,6,7,8,9,10)
(2,5..7,11)=(2,5,6,7,11)
(3..3)=(3)
◆Used 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")
◆Can contain variables or expressions
($var1..$var2+5)
◆Tips:
$fred="Fred";
print(("Hello,".$fred."!\n")x2);
The result is:
Hello,Fred!
Hello,Fred!
4. The output of the 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);
$scalar=@array;#$scalar=3, that is, the length of @array
($scalar)=@array;#$scalar=1, that is, the value of the first element of @array
Note: The length of the Perl array is the number of loops as follows:
$count=1;
while($count<=@array){
print("element$count:$array[$count-1]\n");
$count++;
}
6. Sub-Perl array
@array=(1,2,3,4,5);
@subarray=@array[0,1];#@subarray=(1,2)
@subarray2=@array[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]=@array[3,2,4];#@array=(11,44,33,5,5)now
@array[0..2]=@array[3,4];#@array=(5,5,"",5,5)now
Elements can be exchanged in sub-Perl array form:
@array[1,2]=@array[2,1];
7. Library functions related to Perl arrays
(1)sort--Sort by 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 array
@array2=reverse(@array);
@array2=reversesort(@array);
(3)chop--Perl array de-tail
The meaning of chop is to remove the last character - line break when entering a string by STDIN (keyboard). And if it works on the Perl array, then every element in the Perl array is handled like this.
@list=("rabbit","12345","quartz");
chop(@list);#@list=("rabbi","1234","quart")now
(4) join/split--connect/split
The first parameter of join is the intermediate character used to connect, and the rest is the Perl array of characters to be connected.
$string=join("","this","is","a","string");#The result is "thisisastring"
@list=("words","and");
$string=join("::",@list,"colons");# result is "words::and::colons"
@array=split(/::/,$string);#@array=("words","and","colons")now
3 Hash Array(Associative Array):
Common usage of perl hash
Basic usage
# Initialize %h to empty array %h = {};# Initialize %h to a=>1, b=>2%h = ('a', 1, 'b', 2);# The meaning is the same as above, just another more vivid way of writing. %h = ('a'=>1, 'b'=>2);# If the key is a string, quotes can be omitted. The following line is the same as the above line %h = (a=>1, b=>2);# Use {} to access print "$h{a}\n" # Print 1$h{b} = '2b';print "$h{b}\n" # Print 2b# Delete key with deletedelete $h{b}; # Delete 'b' from $h
Clear hash
undef %h
Get all key values of hash
# Get all keys, the order depends on the hash function, or indisorder
@all_keys = keys %h;
# All key values are arranged from large to small according to the hash value. The comparison of values is a numerical comparison (for example, 10>9)
@all_keys = sort{$h{$b}<=>$h{$a}} (keys %h);
# All key values are arranged from small to large according to the hash value. The comparison of values is a number comparison
@all_keys = sort{$h{$a}<=>$h{$b}} (keys %h);
# All key values are arranged from small to large according to the hash value. The comparison of values is a string comparison (for example, '10' < '9')
@all_keys = sort{$h{$a} cmp $h{$b}} (keys %h);
Determine whether hash contains key
exists($h{$key});
The length of the hash
Want to know how much data a hash stores
$hash_size = keys %h
# Put the length of %h into $hash_size
print scalar kes %h, "\n"
# Print the length of %h. Here we use scalar to return the array length.
Iterate through a hash
while (my ($k, $v) = each %h) {print "$k ---> $v\n";}
Reference Quote
Reference is similar to C/C++ pointer
$h_ref = \%h;
# Get a hash reference%aHash = %{$h_ref};
# Use hash reference as hash with $value = $h_ref->{akey}
# This is the same as %h{akey}
Pass hash to function
Generally, it is passed a reference to the 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;}
The function returns hash, or hash reference (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 choose ifstructure
Perl's conditional control narrative is very similar to C language, allowing users to grasp it quickly. However, Perl has more practical syntax than C language. I use the bottom line to mark it out, and you can tell at a glance.
# Expression is a conditional narrative. Perl and C do not define Boolean datatype.
# Therefore 0 is false, non-0 is ture. In addition, you should pay attention to clearly distinguishing between string operators and numeric operators.
# Code Segment is a bunch 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 instruction, we can use the inverted syntax, which looks relatively concise.
statement if (Expression);
# unless it is if not
statement unless (Expression); Example:
print "HELLO!\n" if ($name eq "friend");
$x-=10 if ($x == 100);
Look! Most of the Perls in C language are available. Those who have learned C can learn Perl effortlessly.
2Circular structure
Perl's loop control narrative is also very similar to C language. Of course, Perl also has some practical syntax as usual:
# Note: The $ font size should be added before the pure quantitative variable, which is different from C.
for($i=0; $i<=10; $i++) {Code Segment}
# foreach is from the shell script that inherits UNIX.
# The first independent variable is a pure quantitative variable, the second independent variable should be enclosed in brackets, and it is a pure quantitative array.
# As the name suggests, it means passing each element in the array to the first independent variable in sequence until all are passed.
# Although it uses different uses from for($i=0; $i<=$#array; $i++), its purpose is to take out each element of the array.
foreach $i (@array) {Code Segment}
# In fact, in Perl, for and foreach can be used in a mixed manner, it depends on the person's habit.
# The following line is equivalent to the first description above, but it is much more concise, so you can try to use it.
for $i (0..10) {Code Segment}
# while control loops and post loops.
while($i<=10) {Code Segment}
do {Code Segment} while(Expression);
# Perl also has the same instructions as the break and continue in C language. Perl calls it last and next (more colloquial).
# last is to jump to the loop where it is located, and next is to jump to the following command and execute the next loop directly.
while(chomp($i=)) {
next if ($i == 5);
last unless ($i > 10);
}
Perl also provides label (marking), which is the goto command. However, experienced programmers do not like to use it, and I do not recommend it to everyone, so I will press it to not talk about it. Those who are interested please check it out. Another thing worth noting is that Perl does not provide switch narratives like C language, but Perl's pattern match has very powerful functions, so I suggest you just use if else narratives to do it.
3Subprogram(Subroutines)
(a) Syntax: sub NAME {Code}
(b) Call subroutine: &NAME(para1, para2,...)
(c) Parameter pass: @_
Perl, like C, uses Call by value, but because Perl does not need to declare variables in advance, it does not need to declare what parameters to be passed when establishing a subroutine. When the main program passes parameters to the subprogram, Perl will place the parameters enclosed in brackets in order in a special global variable @_ array, and the subprogram can use the parameters in the array @_ at will. For example, $_[0] is the first parameter and $_[1] is the second, or use my($a1,$a2,$a3,...) = @_; to extract each parameter. Of course, my @arg=@_; or my %arg=@_; is also OK. Because Perl's syntax is very lively, making the program particularly difficult to maintain, writing annotations has become a very important task. I suggest that you should add a description of this subroutine before each subroutine, especially the parameters that need to be passed should be clearly stated.
(d) Variable Localization:my or local
Usually the variables we define in the program are all global variables, so if you want to localize the variables in the subprogram, you need to add the keyword my or local, for example: my $x=3;. If the variable name used by the subprogram is accidentally the same as the main program, Perl will take the variables in the currently executing subprogram as the priority.
4 I/Oand archive processing
(a) Syntax:
open(FILEHANDLE,"Expression");
close(FILEHANDLE);
The Expression here is a narrative plus file name. If the Expression only has a file name and no narrative plus file name, the preset is 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 $filename file. If it fails to open, print out the message after die and end the program.
open(FILE, $filename) || die "Can't open file $filename : $!\n";
# The following is a very simple writing method, which is equivalent to while($_=){print "$_";}.
print while();
# Remember to close the file at will after opening it, this is a good habit for writing programs.
close(FILE);
#$! and $_ are special variables of Perl, which will be introduced below.
(b) Input:
Perl does not have a function that is specially used for input, because Perl will automatically turn on the standard input device when executing the program, and its filehandle is set to STDIN, so the method to enter data in Perl is to use:
# Perl will not automatically remove the ending CR/LF, which is different from C, so you need to use the chomp function to help you remove it.
# People often forget this action, which leads to the result different from what you think, so pay special attention.
$input=<STDIN>; chomp $input;
# The following is a simpler way of writing.
chomp($input=<STDIN>);
(c) Output: print "variables or string";
Perl also has the printf() function, and the syntax is exactly the same as C language, so I won't introduce it much. Perl also has a print function, which is more convenient and more useful than printf(), so you can't put it down. Output is nothing more than outputting to the screen or archive, and it is easier to understand by using examples.
# No need to specify the data type of the variable, isn't this much more convenient than printf()?
print "Scalar value is $x\n";
# . is the operator of string addition, the upper and lower lines are equivalent.
print "Scalar value is " . $x . "\n";
# Method to output to archive.
print FILE "print $x to a file.";
# The following is the special usage of print, learned from the usage of shell script:
print<XXX
This trick is called here document. XXX can be any identifier you take. The words between the identifiers will be output as you write, just like a \ tag. And when the beginning of a line is the identifier you took by XXX, the output will stop.
XXX
Perl also has special characters starting 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 be noted that Perl incorporates the usage convention of unix shell script. Strings enclosed in double quotes ("") will be expanded first, but the characters after the backslash (\) will not be expanded, and they are treated as general characters. A string enclosed in single quotes ('') will not expand at all. A string enclosed in reverse single quotes (``) will be executed as a command-line instruction, which is equivalent to system(). Beginners often get confused, but after getting used to it, they will feel that it is not possible to distinguish this way. For 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
Called by &.
2. Perl parameters
Perl naturally supports variable number of parameters.
Inside the function, all parameters are placed in the array @_ in order, and inside the function, $_[0] represents the first one of the function
Parameters, and so on.
3. shift
shift followed by an array, which means returning the first value of the array. The array is also changed, and its first element is popped
out.
Demo Code 1 (find the maximum value):
#!/usr/bin/perl -w
use strict;
# Call the function max to obtain the maximum value of a set of values and output it.
my $maxCnt = &max(11,22,33);
print "maxCnt=$maxCnt\n";
sub max {
# Use traversal algorithm. First assign the first value in the parameter to $currentMaxCnt.
# @_ is the default array containing all parameters of this function [such as (11,22,33)].
# shift @_ has two results: 1. Use the first value in the array @_ as the return value (assigned to
$currentMaxCnt). 2. Pop up the first value of the @_array [after that the value of @_ becomes (22,33)].
my $currentMaxCnt = shift @_;
# When using shift in the function, @_ can be omitted. The above code can also be written like this.
# my $currentMaxCnt = shift;
# Iterate through the entire @_array.
foreach ( @_ ) {
# $_ represents the element currently traversed in the array @_.
if ( $_ > $currentMaxCnt ) {
# If you find that the current array element is larger than $currentMaxCnt, then reassign $currentMaxCnt to the current value
element.
$currentMaxCnt = $_;
}
}
# The function returns the value of the scalar $currentMaxCnt.
return $currentMaxCnt;
}
Demonstration code two (sum):
#!/usr/bin/perl -w
use strict;
# Find the sum of a set of numbers and print it.
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) accordingly
(my $first, my $second, my $third) = @_;
# Returns its sum value. Disadvantages: If you are finding the sum of four parameters, you can still only give the sum of the first three.
return $first + $second + $third;
}
# Method 2
sub sumarg {
# $_[0] represents the first element of the parameter array @_. The rest and so on.
my $first = $_[0];
my $second = $_[1];
my $third = $_[2];
# Returns its sum value. Disadvantages: Same as sumvar. Just learn this usage of $_[0] through here.
return $first + $second + $third;
}
# Method 3, you can have as many parameters as you like. All can seek harmony.
sub sumgod{
my $s = shift @_;
foreach ( @_ ) {
$s = $s + $_;
}
# Same as previous function max.
return $s;
}
8Summarize
I sorted out some symbols, usages, functions, libraries and so on that I think I use more, these are very basic
, but "memorizing" it will be very helpful for improving efficiency.
Data operation
*$ - Declare and reference variables with a scalar
* @ - Declare and reference a list, but when accessing a member of a list, you need to use $ListName[index]
* % - Declare and reference a hash table, but when accessing a hash member, you need to use $HashName
{key}
Special variables
* $0 - The file name of the currently running script
* @ARGV - List of command line parameters for the currently running script
* $_ - Default variable, such as the current variable in the loop
* @_ - List of input parameters for function
* %ENV - System environment variable
* @INC - Perl's Include path list, we can add our own directory to this list to facilitate the introduction
Use custom libraries
* $! - The current system prompts, error message
* $^O - The name of the operating system
* STDIN,STDOUT,STDERR - The default handle for input and output, can be customized for certain
* => - When declaring a hash, it can be used to clearly express the corresponding relationship of key=>value
* $^I- Specifies the suffix name of the backed-up file. In this way, the modified file will automatically save a secondary file with this suffix name.
Book
Special usage
* &Sub - Call a function. Although Perl has some rules that allow you to omit the & symbol here at some point,
It is for consistency consideration, so I will use this method to call custom functions.
* $# - Used to obtain the maximum index of the modulo array. Generally, -1 can also be used to represent the last element.
index
* qw() - Quickly declare an array of strings that can omit those annoying quotes
Regular expressions
* $ - Get the match captured by brackets
* $`, $&, $' - Get the matching string, and its two parts before and after
* ^,$ - The whole position of the string, used as positioning
Common functions
* pop, push, shift, unshift, reverse - list operation function
* keys, values, exists, each, delete - hash operation function
* chomp, split, join, index, substr, sort - string operation function
* sprintf,printf, print - Format output function
* system, exec, `` - System command calls function
* glob, unlink, mkdir, rmdir, rename,chmod,chown, open, close, opendir,
closedir - File system operation function
* stat, lstat,localtime,gmtime,utime - Document attributes, time-related functions
* hex, oct - function that converts binary, octal, hexadecimal numbers into decimal
* grep, map - list advanced operation functions
The detailed introduction of these functions can be done through the command:
#perldoc -f functionname
Checked
Commonly used libraries
* File::Basename - Get the file name or file path according to path
* File::Spec - Combine the file name and path into the entire path
* File::Find - Recursively traverse all files in a directory
* XML::Simple - Use a complex structure to represent an XML file, which is quite convenient to use
* Time::HiRes - is often used to calculate the time taken by an operation
* Getopt::Long - Used when scripts require complex input parameters and options
* Cwd - Get the current working directory
* IO::File - File Operation
* Win32 - I will use it when I need to call some Windows API