I. Data Types(Data type):
Perl has four data types: Scalar (variable), Scalar Array (Array), Hash Array (Hash), and References (pointer ), it seems to be rare, but it is more than enough to use it. Especially when writing Perl programs, you do not need to declare variables in advance. This is very convenient for those who are new to programming languages. However, in order to facilitate program debugging and maintenance in the future, I suggest you develop the habit of declaring variables in advance.
1 Scalar(Pure variable ):
Pure variables are the most basic data type in Perl. They can represent a character, String, integer, or even floating point. Perl regards them as the same! You can even use it together. That's incredible. For example:
# Comments are added at the beginning of the well font size.
# Starting with a pure quantitative variable of $.
# My is a way to declare variables, which can enable regionalization of variables.
# If I or local is not added when declaring a variable, Perl uses it as a global variable.
# Traditionally, We will enclose the string in double quotation marks, and the value will not be enclosed by quotation marks.
My $ x = "abc ";
'My $ x = 123;
'My $ x = 4.56;
1-1Common Operators
1) Arithmetic Operators
+ (Plus),-(minus), * (multiplication),/(Division), ** (power), % (remainder),-(negative)
(1) The result of power (**) cannot exceed the value range. When the index is decimal, the base number cannot be negative. For example, 25 ** 1.5 = 125, (-25) ** 1.5 =? (Not valid)
(2) The remainder (%) operand is an integer. Otherwise, it must be truncated. The second number cannot be 0 (because the divisor cannot be 0)
(3) negative (-)-$ a = $ a * (-1)
In addition, when a string is involved in the operation and needs to be converted to an integer, if it cannot be converted to an integer, the value is 0. Example: '2' + 1 = 3, 'A' + 1 = 1
2) numeric comparison Operators
<(Less than), = (equal to),> (greater than), = (equal to), <= (less than or equal to), >=( greater than or equal ),! = (Not equal to), <=> (comparison)
(1) =: Comparison calculation. The comparison result is true or non-zero, false or zero.
(2) <=>: Comparison calculation 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 converts the operand to an integer. If it cannot be converted to an integer, It is 0.
(4) The floating point number is not accurate. Do not compare the numbers with similar values. Otherwise, the result is unexpected.
3) string comparison Operators
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) character string comparison principle: Compare the numbers in alphabetical order, and <upper-case letters <lower-case letters (a small-z large)
(2) string comparison order: the string is compared from left to right. 'Azz' <'bc' (that is, a and B are compared first, and then z and c are compared)
(3) When a string is the prefix of another string, the length is large. Example: dog <doghouse
(4) A string can be carried from the right to the left, with letters and numbers respectively.
(5) convert the operand into a string automatically. 123 lt 45 => '000000' lt '45'
(6) cmp is equivalent to <=>. The result is-, 1.
For example: $ str1 = "a", $ str2 = "a", print ($ str1 cmp $ str2) => 0
For example: $ str1 = "a", $ str2 = "B", print ($ str1 cmp $ str2) ==>-1
For example: $ str1 = "B", $ str2 = "a", print ($ str1 cmp $ str2) ==> 1
(7) null strings, 0, Undef, all of which are false.
Example: The following comparison results
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
''G'' # True
4), string connection (.), character/string repetition (x)
(1) connection ("."), for example: $ a = 'A'. 'B'; => 'AB'
You can directly write print $ a $ B => print $ a. $ B During print, but the principles of the two are different.
(2) Repeat ("x"). Note: There are spaces before and after (objective: to separate them from the variable name), for example, 'A' x 5 = 'aaaaa ', if the number of repetitions is less than 1, an empty string is returned.
For example: "5" x 4, that is: "5555"
For example, "love" x (4 + 1) is: "lovelovelovelovelove"
For example: "4.8" x 4, that is: "4.84.84.84.8"
For example: 6.1x3, that is: "6.16.16.1"
That is, a string is displayed on the left and the number of times the string appears on the right.
5), logical operators (& (and), | (or), and ),! (Not), xor (exclusive or)
(1) Calculate the value on the left and then the value on the right.
(2) & and have different priorities, but unless in special circumstances, it is difficult to make a difference.
6) bitwise operators
& (By bit and), | (by bit or ),~ (Not by bit), ^ (by bit or exclusive), <(left shift),> (right shift)
(1) the operand is a binary integer. If it is a decimal number, it is truncated to an integer.
(2) <shift left. after removal, the empty space is filled with 0, and the value is 2 * N times of the original value (for example, z <4, then z = z * (4 to the power of 2 ))
(3)> right shift, first fill 0, the value is half of the original value (and take an integer) (for example, z> 4, then z = z/(the power of 2 ))
7) assignment operator
=, + =,-=, * =,/=, % =, ** =, & =, | =, ^ =,. =
(1) $ a + = 1 => $ a = $ a + 1
(2) $ a = $ B = 3; => $ a = 3; $ B = 3;
(3) mix ($ a = $ B) + = 3 ;=>a = $ B; $ a = $ a + 3; (not recommended)
8), auto-increment (++), auto-increment (--)
(1) do not use this operator on both sides of the variable: ++ $ var --
(2) do not use $ var2 = $ var1 ++ $ var1 in the same expression after the variable auto-increment or subtraction;
(3) It can be used for the auto-increment of a string, which is a bit when z, Z, or 9. $ A = 'caz'; $ a ++ ;=>$ a = 'CBA ';
(4) it cannot be used for string auto-subtraction. When $ a -- is used, the character is converted to 0 before auto-Subtraction by number.
(5) If a string contains non-alphanumeric characters or numbers in a letter, the auto-increment value is first 0 and then auto-increment.
Example: $ a = 'AB * C'; $ a ++ ==>$ a = 1;
Example: $ a = 'ab5c '; $ a ++ ;=>$ a = 1;
(6) pre-increment $ B = ++ $ a, $ a First Auto increment and then assign a value, then increment $ B = $ a ++; $ a first assign a value and then auto increment; otherwise, likewise
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 cannot be used for the variable after calculation. Example: ($ a + $ B) ++
9), comma (equivalent to: Write two statements in one line)
Applicability: used only when two statements are closely related
For example: $ a + = 1, $ B = $ a ;=>$ a + = 1; $ B = $;
Example: $ a = "ab5c", print $ a. "\ n ";
10. Conditional Operators
Condition? True: false
(1) three operands: Calculate the conditional expression first. If it is true, execute the operation on the left of:. If it is false, execute the operation on the Right :.
Example: $ result = $ var = 0? 14: 7;
(2) For simple conditions
(3) The conditional expression is used on the left of =.
Example: $ condvar = 43? $ Var1: $ var2 = 14;
Example: $ condvar = 43? $ Var1 = 14: $ var2 = 14;
3. Operator priority (precedence -- priority)
When several different operators appear in an expression, which one is calculated first and which is then calculated
Example: $ condvar = 43? $ Var1: $ var2 = 14; (calculate the conditions first and then assign values)
Example: $ x = $ a = $ B; (calculate the relationship first and then assign a value)
For example: $ x = 0 | $ y/$ x> 5; (first calculate the division, then calculate the value greater than, then calculate the value equal to, and finally calculate the relationship or)
Example: $ result = 11*2 + 6 ** 2 <2; (calculate the power first, then calculate the multiplication, then calculate the addition, then calculate the Left shift, and finally calculate the value)
(1) The general priority is as follows: the highest auto-incrementing auto-subtraction, the single-operand is higher than the multi-operand, the number operation> the comparison operation (the number comparison and the string comparison)> bitwise operations> value assignment operations> logical operations
(2) number operation: Power> */> +-
(3) Comparison: <(less than),> (greater than) is higher than (= and! =)
2 Scalar Array:
Perl array variables and list concepts. A list is a sequence of values contained in parentheses. It can be any value or empty, and the list is stored in Perl array variables, unlike simple variables, Perl array variables start with the character.
Perl array variables and lists
I. List
The list is a sequence of values contained in parentheses. It can be any value or empty, for example:
(1, 5.3, "hello", 2), empty list :().
Note: The list containing only one value (for example, :( 43.2) is different from the value itself (I .e., 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 ")
Ii. Perl array-list Storage
The list is stored in Perl array variables. Unlike simple variables, Perl array variables are prefixed with characters "@", such:
@ Array = (1, 2, 3 );
Note:
(1) When creating a Perl array variable, 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 both Perl
Array variables and simple variables, such:
$ Var = 1;
@ Var = (11, 27.1, "astring ");
But this is easy to confuse, so it is not recommended.
1. Perl array access
◆ Access the values in the Perl array by subscript. The subscript of the first element is 0. Try to access a non-existent Perl array element
The result is NULL, but if an element that exceeds the Perl array size is assigned a value, the Perl array automatically grows.
To NULL. For example:
@ 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;
◆ Assign values to the list using the Perl Array
@ List1 = (2, 3, 4 );
@ List2 = (1, @ list1, 5); # @ list2 = (1, 2, 4, 5)
◆ Assign values to simple variables in the Perl Array
(1) @ array = (5, 7, 11 );
($ Var1, $ var2) = @ array; # $ var1 = 5, $ var2 = 7, 11 ignored
(2) @ array = (5, 7 );
($ Var1, $ var2, $ var3) = @ array; # $ var1 = 5, $ var2 = 7, $ var3 = "" (null)
◆ Assign values to variables from standard input (STDIN)
$ Var = <STDIN>;
@ Array = <STDIN>; # ^ D indicates the end input symbol.
2. square brackets and variable replacement in the string
"$ Var [0]" is the first element of the Perl array @ var.
"$ Var \ [0]" Escape 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 the text: $ {var }.
3. List scope:
(1 .. 10) = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
(2, 5 ..) = (, 11)
(3 .. 3) = (3)
◆ Used for real numbers
(5.3. 2.1) = (3.1, 4.1, 5.1)
(1.6) = ()
◆ String
("Aaa"... "aad") = ("aaa", "aab", "aac", "aad ")
@ Day_of_month = ("01" .. "31 ")
◆ Variables or expressions can be included
($ Var1.. $ var2 + 5)
◆ Tips:
$ Fred = "Fred ";
Print ("Hello,". $ fred ."! \ N ") x2 );
The result is:
Hello, Fred!
Hello, Fred!
4. Perl array output:
(1) @ array = (1, 2, 3 );
Print (@ array, "\ n ");
Result:
123
(2) @ array = (1, 2, 3 );
Print ("@ array \ n ");
Result:
123
5. Length of the 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 can be programmed 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 [] = ("string", 46); # @ array = ("string",) now
@ Array [0 .. 3] = (11,22, 33,44); # @ array = (11,22, 33,44, 5) now
@ Array [, 3] = @ array [, 4]; # @ array = (, 5, 5) now
@ Array [0 .. 2] = @ array [3, 4]; # @ array = (5, 5, "", 5, 5) now
You can use a sub-Perl array to exchange elements:
@ Array [1, 2] = @ array [2, 1];
7. database functions related to Perl Arrays
(1) sort -- sort by character
@ 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 the Perl Array
@ Array2 = reverse (@ array );
@ Array2 = reversesort (@ array );
(3) chop -- Perl array Tail removal
The significance of chop is to remove the last character-line break when STDIN (keyboard) is entered. If it is applied to the Perl array, this is done for every element in the Perl array.
@ List = ("rabbit", "12345", "quartz ");
Chop (@ list); # @ list = ("rabbi", "1234", "quart") now
(4) join/split -- join/split
The first parameter of join is the intermediate character used for the connection, and the rest is the Perl array of characters to be connected.
$ String = join ("", "this", "is", "a", "string"); # The result is "thisastring"
@ List = ("words", "and ");
$ String = join (":", @ list, "colons"); # The result is "words: and: colons"
@ Array = split (/: //, $ string); # @ array = ("words", "and", "colons") now
3 Hash Array (Associative Array):
Common perl hash usage
Basic usage
# Initialize % h as an empty array % h ={}; # use an array to initialize % h as a => 1, B => 2% h = ('A', 1, 'B', 2); # The meaning is the same as above, but it is another way of more visual 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 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 using deletedelete $ h {B}; # Delete 'B' from $ h'
Clear hash
Undef % h
Obtain all hash key values.
# To get all keys, the order depends on the hash function, or out of order.
@ All_keys = keys % h;
# All key values are sorted by hash value from large to small. Comparison of values is numerical comparison (for example, 10> 9)
@ All_keys = sort {$ h {$ B} <= >$ h {$ a} (keys % h );
# All key values are sorted by hash value from small to large. Value Comparison is numeric comparison
@ All_keys = sort {$ h {$ a} <= >$ h {$ B} (keys % h );
# All key values are sorted by hash value from small to large. Value Comparison is string comparison (for example, '10' <'9 ')
@ All_keys = sort {$ h {$ a} cmp $ h {$ B} (keys % h );
Determine whether the hash contains the key
Exists ($ h {$ key });
Hash Length
Want to know how much data a hash stores
$ Hash_size = keys % h
# Put % h in $ hash_size
Print scalar kes % h, "\ n"
# Print the length of % h. Scalar is used to return the array length.
Traverse a hash
While (my ($ k, $ v) = each % h) {print "$ k ---> $ v \ n ";}
Reference
Reference is similar to a C/C ++ pointer.
$ H_ref = \ % h;
# Obtain 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, a reference is passed to the function.
% H = (); $ h {a} = 1; foo (\ % h) print $ h {B}, "\ n ";
# Print 2.
This value is from function foo () sub foo {my ($ h) =@_; print $ h-> {a}, "\ n ";
# Print out 1 $ h-> {B} = 2 ;}
The function returns hash or hash reference)
The function returns the hash value.
Sub foo {my % fh; $ fh {a} = 1; return % h;} my % h = foo (); print
II Control Structure(Control Statements)
1SelectIfStructure
Perl's conditional control statement is similar to the C language, allowing users to quickly master it. However, Perl has some more practical syntaxes than the C language. I use the bottom line to mark them.
# Expression is a conditional statement. Perl and C do not define a Boolean data type (Boolean datatype ),
# Therefore, 0 is false, and non-0 is true. In addition, note that the string and numeric operators should be clearly divided.
# Code Segment is a pile of commands enclosed in braces, that 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 command (statement), we can use the inverted syntax, which looks concise.
Statement if (Expression );
# Unless is if not
Statement unless (Expression); example:
Print "HELLO! \ N "if ($ name eq" friend ");
$ X-= 10 if ($ x = 100 );
Look! Most of the Perl in C language is available. People who have learned C can learn Perl without any effort.
2Loop Structure
The cycle control of Perl is also similar to that of C language. Of course, as mentioned in the example, Perl also has some more practical Syntax:
# Note: A $ font size must be added before the pure variable. This is different from the C language.
For ($ I = 0; $ I <= 10; $ I ++) {Code Segment}
# Foreach is a UNIX shell script,
# The first independent variable is a pure variable, and the second independent variable should be enclosed in parentheses, which is a pure amount array,
# As its name implies, each element in the array is passed to the first independent variable in sequence until all elements are passed.
# It is different from for ($ I = 0; $ I <= $ # array; $ I ++), but it is used to retrieve each element of the array.
Foreach $ I (@ array) {Code Segment}
# In Perl, for and foreach can be used in a mixed manner, so we can see that people are used to it.
# The following line is equal to the first one described above, but it is much more concise. You can try to use it.
For $ I (0 .. 10) {Code Segment}
# While control loop and post loop.
While ($ I <= 10) {Code Segment}
Do {Code Segment} while (Expression );
# Perl has the same commands as break and continue in C language. Perl calls it last and next (more colloquial ).
# Last is the current loop, and next is to skip the following command to directly execute the next loop.
While (chomp ($ I = )){
Next if ($ I = 5 );
Last unless ($ I> 10 );
}
Perl also provides the label syntax, that is, the goto command. However, experienced programer does not like to use it, and I do not recommend it to anyone. If you are interested, please check it yourself. It is worth noting that Perl does not provide a switch statement like the C language, but Perl's pattern match function is very powerful, so I suggest you simply use the if else statement.
3Subroutine(Subroutines)
(A) Syntax: sub NAME {Code}
(B) Call Subroutine: & NAME (para1, para2 ,...)
(C) parameter transfer :@_
Like C, Perl uses the Call by value method. However, because Perl does not need to declare variables in advance, it does not need to declare the parameters to be passed when creating a subroutine. 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 use the parameters in the array @ _. For example, $ _ [0] is the first parameter, $ _ [1] is the second parameter, or use my ($ a1, $ a2, $ a3 ,...) = @ _; to retrieve parameters. Of course, my @ arg = @ _; or my % arg = @ _; is also acceptable. Because the Perl syntax is very lively, it makes the program very difficult to maintain, so writing comments becomes a very important task. I suggest you add the description of this subroutine before each subroutine, especially the parameters to be passed.
(D) Variable Localization: my or local
Generally, the variables we define in the program are all global variables, so if you want to regionalize the variables in the subroutine, you need to add the my or local keyword, for example, my $ x = 3 ;, if the name of the variable used by the subroutine is the same as that of the main program, Perl takes precedence over the variables in the subroutine currently being executed.
4 I/OAnd Archive Processing
(A) Syntax:
Open (FILEHANDLE, "Expression ");
Close (FILEHANDLE );
The Expression here is a description plus the file name. If Expression only contains the file name without a description, it is read-only by default. The Expressions statement is 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:
# Enable the file $ filename. If the file fails to be opened, the message after the die is printed and the program is ended.
Open (FILE, $ filename) | die "Can't open file $ filename: $! \ N ";
# The following is a very simplified writing method, which is equivalent to while ($ _ =) {print "$.
Print while ();
# Remember to close the archive after it is enabled. This is a good habit of writing programs.
Close (FILE );
# $! And $ _ are special variables of Perl, which will be described below.
(B) Input:
Perl has no special input function, because Perl automatically enables the standard input device when executing the program, and its filehandle is set to STDIN. Therefore, the method to input data in Perl is to use:
# Perl does not automatically remove the ending CR/LF, which is different from the C language. Therefore, use the chomp function to remove the ending CR/LF.
# You will often forget this action, which leads to different results than you think. Pay special attention to it.
$ Input = <STDIN>; chomp $ input;
# The following is a concise method.
Chomp ($ input = <STDIN> );
(C) Output: print "variables or string ";
Perl also has the printf () function, which has the same syntax as the C language. I will not introduce it more. Perl also has a print function, which is more convenient and easy to use than printf. Output is similar to Output to a screen or file. It is easier to understand it by using examples.
# No need to specify the data type of the variable. Isn't this much easier than printf?
Print "Scalar value is $ x \ n ";
#. It is the operator of string addition. The upper and lower rows are equivalent.
Print "Scalar value is". $ x. "\ n ";
# Method for outputting data to an archive.
Print FILE "print $ x to a file .";
# The special usage of print is as follows. Learn the usage of shell script:
Print <XXX
This is called here document. XXX can be any identifier you take. Words between identifiers are output as you write, just like \ tags. When a row starts with XXX, the output is stopped.
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
In addition, it should be noted that Perl integrates the usage conventions of unix shell scripts. Strings enclosed in double quotation marks ("") are expanded first, but the backslash (\) the subsequent characters are not expanded and treated as common characters. Strings enclosed by single quotes ('') are not expanded at all. Strings enclosed by single quotes ('') are executed as command column commands and are equal to system () same. Beginners often get confused, but after getting used to it, they will feel that it is not possible to clearly distinguish it. 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 Functions
Through & call.
2. Perl Parameters
Perl supports variable parameters.
In the function, all parameters are placed in the array @ _ in order. Inside the function, $ _ [0] indicates the first function.
Parameters, and so on.
3. shift
Shift is followed by an array, indicating that the first value of the array is returned. The array is also changed, and the first element is
Output.
DEMO code 1 (maximum value ):
#! /Usr/bin/perl-w
Use strict;
# Call the function max to obtain the maximum value of a set of values and output them.
My $ maxCnt = & max (11,22, 33 );
Print "maxCnt = $ maxCnt \ n ";
Sub max {
# Use the traversal algorithm. First, assign the first value to $ currentMaxCnt.
# @ _ Is the default array containing all parameters of this function [such as (, 22, 33.
# Shift @ _ has two results: 1. Use the first value in the array @ _ as the return value (assigned
$ CurrentMaxCnt). 2. pop up the first value of the @ _ array [change the value of @ _ to ()].
My $ currentMaxCnt = shift @_;
# When shift is used in the function, @ _ can be omitted. The above code can also be written as this.
# My $ currentMaxCnt = shift;
# Traverse the entire @ _ array.
Foreach (@_){
# $ _ Indicates the elements currently traversed in the array.
If ($ _> $ currentMaxCnt ){
# If you find that the current array element is larger than $ currentMaxCnt, assign $ currentMaxCnt to the current
Element.
$ CurrentMaxCnt =$ _;
}
}
# The Return Value of the function is scalar $ currentMaxCnt.
Return $ currentMaxCnt;
}
DEMO code 2 (SUM ):
#! /Usr/bin/perl-w
Use strict;
# Calculate and print the sum of a group of numbers.
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) = @_;
# Return the value. Disadvantage: if we want to calculate the sum of the four parameters, we can only provide the sum of the first three.
Return $ first + $ second + $ third;
}
# Method 2
Sub sumarg {
# $ _ [0] indicates the first element of the parameter array. And so on.
My $ first =$ _ [0];
My $ second = $ _ [1];
My $ third =$ _ [2];
# Return the value. Disadvantage: similar to sumvar. You can only use $ _ [0] Here.
Return $ first + $ second + $ third;
}
# Method 3: there can be any number of parameters. And.
Sub sumgod {
My $ s = shift @_;
Foreach (@_){
$ S = $ s + $ _;
}
# Same as the previous function max.
Return $ s;
}
8Summary
I sorted out some of the symbols, usage, functions, libraries that I thought I was using. These are very basic.
But it is very helpful to improve efficiency.
Data Operations
* $-Declare and reference a variable using a scalar
* @-Declare and reference a list. However, when accessing a list member, you must use $ ListName [index].
* %-Declare and reference a hash table, but when accessing a hash member, you need to use $ HashName
{Key}
Special Variables
* $0-name of the file currently running the script
* @ ARGV-List of command line parameters of the current script
* $ _-Default variables, such as the current variable in the loop
*-Function input parameter list
* % ENV-system environment variable
* @ INC-Perl's Include path list. We can add our own directories to this list to facilitate reference.
Use a custom Library
* $! -Current System prompt, error message
* $ ^ O-operating system name
* STDIN, STDOUT, and STDERR-default handle of input and output, which can be customized
* =>-When declaring a hash, it can be used to explicitly express the correspondence between key => value.
* $ ^ I-specifies the suffix of the backup file. In this way, the modified file will automatically save a copy with the suffix
Ben
Special usage
* & Sub-calls a function. Although some Perl rules allow you to omit the & symbol
It is in consideration of consistency, so I always use this method to call custom functions.
* $ #-Used to obtain the maximum index of the modulo array. Generally, you can use-1 to represent the last element.
Index
* Qw ()-quickly declare a string array, which can omit annoying quotation marks
Regular Expression
* $-Get matching captured by parentheses
* $ ', $ &, $'-Obtain the matched string and the first and second parts
* ^, $-Start and end position of the string, used for locating
Common functions
* Operation functions of pop, push, shift, unshift, and reverse-list
* Operation functions of keys, values, exists, each, and delete-hash
* Chomp, split, join, index, substr, sort-string operation function
* Sprintf, printf, print-format the output function
* System, exec, ''-system command to call a function
* Glob, unlink, mkdir, rmdir, rename, chmod, chown, open, close, opendir,
Closedir-file system operation functions
* Stat, lstat, localtime, gmtime, utime-document attributes, time-related functions
* The hex, oct-binary, octal, and hexadecimal values are converted into decimal functions.
* Grep, map-list advanced operation functions
For more information about these functions, run the following command:
# Perldoc-f functionname
Check
Common Libraries
* File: Basename-get the File name or File path based on path
* File: Spec-combines all paths based on the File name and Path
* File: Find-recursively traverses all files in a directory
* XML: Simple-represents an xml file in a complex structure, which is quite convenient to use.
* Time: HiRes-often used to calculate the Time consumed by an operation
* Getopt: Long-used when the script requires complex input parameters and options
* Cwd-get the current working directory
* IO: File-File Operations
* Win32-I will use it when I need to call some Windows APIs