Perl language learning - Introduction
The introduction includes but is not limited to the following contents
- Introduction to Perl
- Version history
- First Perl program
- Basic data types of Perl
- Perl's operation operator and judgment operator
- Perl array operation
- Perl control structure statement
- Perl subroutine
Note: Although the logic controller is not mentioned in this article, the logic controller of Perl is basically consistent with the logic control symbols of C or JAVA, and supports the operation of and or not, that is! |& There is not much difference in the use of these symbols. Therefore, this is omitted in this article. Please refer to the relevant documents if necessary
1 Introduction to Perl
-
Unix system comes with Perl, which is called "Unix toolbox"
-
It is called "Practical Extraction and Report Language"
-
Also known as the pathologically eclectic garbage Lister
-
Perl motto: There's More Than One Way To Do It!
-
Perl is good at text processing and system management. It is not suitable for real-time embedded system programming, underlying operating system development (such as driver development), complex multilinear shared memory applications and extremely large applications.
-
The invention history of Perl
- Larry wants to write a Bug reporting system for a file system similar to newsgroups, which is a * * general-purpose multi-purpose tool**
- It is a language evolved from C, sed, awk, Unix shell and other languages.
- Perl is a language optimized for scanning arbitrary text files, obtaining information from these text files, and printing reports based on this information.
- It aims to be practical (easy to use, efficient and complete) rather than beautiful (beautiful and compact).
-
Perl features
- advantage
- Easy to use
- unrestricted
- No limit on data size, only limited to computer storage
- Almost everything can be done in Perl
- Excellent performance
- Portability: most operating systems support Perl
- Module extension
- function
- shortcoming
- Code ugly (the mascot is camel - > useful and ugly)
- Confusion caused by multilingual collections (four unlike)
- Poor readability
- advantage
-
Some features of memory enhancement
- Perl programs are about 30% - 70% longer than the equivalent C program
- Suitable for writing "ugly but usable" one-time programs in three minutes
- Good at dealing with "about 90% of word processing related" problems
Try to describe Perl in one sentence
- Is that ok?
Try to describe Perl in one word
- a powerful and unconstrained style
1.1 Perl version
1.1.1 historical version
No relevant information is available, which will be supplemented later
1.1.2 main version branches: Strawberry Perl and ActiveState Perl
- files are different size
- Strawberry Perl: trawberry Perl downloads more than 80 installation files.
- Active Perl: ActiveState Perl is only about 20M
- Different content
- Strawberry Perl: Strawberry Perl contains many modules in CPAN.
- Active Perl: contains four sets of development tool programs including Perl for Win32, Perl for ISAPI, PerlScript and Perl Package Manager, which allows users to write CGI programs suitable for unix, windows and linux systems.
- Different characteristics
- Strawberry Perl: 100% open source Perl for Windows. Using modules from CPAN does not require binary packages.
- Active Perl: ActiveState provides a free community version and a commercially supported Perl for Win32 and Perl binary distribution.
1.1.3 CPAN
Comprehensive Perl Archive Network
Perl comprehensive collection network( http://search.cpan.org/ )
perl module extension is used to download various extension modules and documents based on perl.
CPAN also requires additional installation
yum install -y perl-CPAN
The use of cpan is similar to that of database. You need to enter the corresponding operation interface and use perl -MCPAN -e shell to enter the operation interface
The specific modules and installation commands will be discussed later.
1.2 Perl installation
https://www.perl.org/get.html Log in to the official website to download the corresponding version for installation, and print the version to verify the installation
perl -v
2 first Perl program
Programmers who have studied shell scripting language will be helpful in learning perl.
Perl is a plain text file. You can use any text editor to write Perl programs, such as txt, vm/vim, notepad, etc
mkdir -p /data/test/ vim /data/test/HelloWorld.pl
typing
#!/usr/bin/perl print "Hello world!\n";
After saving, run the file in perl.
Note: if a non administrator user is used, please note whether the current user has execution permission
perl /data/test/HelloWorld.pl
You can see that the program will output the corresponding characters
Continue to read some supplementary knowledge points - > for colleagues who have just come into contact with scripting language
-
Perl's use keyword, you will frequently see use 5.014 in the rest of this article; use warings; use utf8; use strict and other codes. The use keyword is actually the loading of Perl program modules, which is the key usage of Perl pluggable programming.
In the above code, for example, use 5.014 indicates the support of Perl 5 version number 14, and the say function can only be used normally in this version.
There's a lot to expand on the use keyword, but for now you just need to remember that it's used to introduce module support for Perl programs.
For Perl use keyword, here are some reference documents:
-
http://blog.chinaunix.net/uid-608135-id-4439772.html The underlying implementation of the use keyword and its usage are explained here
-
http://bbs.eetop.cn/thread-613055-1-1.html It is mentioned here that the execution stages of the use keyword and the require keyword are different
-
-
#!/ usr/bin/perl, you will notice this line in the header of every Perl program. If you are not familiar with Linux and scripting language, you may be confused about it. This is the specification of the script language in the Linux operating system. It is used to tell the operating system what interpreter to call when executing the file. You can see this difference in the first program written above
-
This call procedure refers to when the script file is run directly, such as
./test.pl
No prefix points to test. In the current folder PL script, the operating system will find the interpreter from the interpreter path declared in the first line, and use the interpreter to execute the script. (you need to give permission to the file to use this method)
-
If instruction programming
perl ./test.pl
If the interpreter that executes the script is explicitly declared, the header line can be written without writing. (use this method to bypass permission restrictions)
-
3 Perl data
Include the following
- Two basic data structures (floating point number and string)
- Data operation and comparison operators
- Type conversion of floating point numbers and strings
- Boolean definition undef, 0, ""
- Assignment and scope of variables
- Lists and arrays and their assignments
- Common operators for lists and arrays
- pop
- push
- shift
- unshift
- splice
- reverse
- sort
- each
3.1 figures
There is no integer value inside Perl. All numbers will be stored as "double precision floating point number" (double type compiled by gcc),
It can be expressed directly as an integer. For example, 5 -- > is interpreted as 5.00
Note: Perl uses integers internally, but programmers don't need to care. Secondly, Perl can compile integers using the integer compilation command.
Perl allows you to insert underscores between integers, For example, it represents a bank card, 6217_ 0013_ 0000_ 0992_ 328, so it looks very clear (if calculation is not required, it is recommended to use string representation for such data)
3.1.1 number operator
Perl supports addition, subtraction, multiplication and division, modular operation and power operation
Digital operation | Operator | Example | Example operation results |
---|---|---|---|
addition | + | 2 + 3 | 5.00 |
subtraction | - | 5.1 - 2.4 | 7.50 |
multiplication | * | 1 * 2 | 2.00 |
division | / | 14 / 7 | 2.00 |
Modular operation | % | 5 % 2 | 1.00 |
exponentiation | ** | 2 ** 3 | 8.00 |
3.1.2 number comparison operator
Digital comparison operation | Operator | Example | Example operation results |
---|---|---|---|
equal | == | 1 == 1 | really |
Unequal | != | 1 != 1 | false |
less than | < | 1 < 1 | false |
greater than | > | 1 > 1 | false |
Less than or equal to | <= | 1 <= 1 | really |
Greater than or equal to | >= | 1 >= 1 | really |
The Boolean definition of true and false will be described in later chapters
3.2 string
Perl strings are text surrounded by single quotation marks' 'or double quotation marks'', such as: 'a character', 'still character';
Perl has an unlimited string length. (embodies one of the Perl principles: no memory limit) 0 - memory Max
Perl characters fully support Unicode. (declaration coding format required)
use charset function to declare the encoding format of the file
The encoding(charset) function specifies the encoding format for a specific behavior
Difference between single and double quotation marks of string
-
Single quote ''
- Except for single quotation marks and backslashes / characters in single quotation marks, all characters in single quotation marks represent themselves.
- To represent a backslash, you need two consecutive backslashes. To represent the single quotation mark itself, follow the backslash with the single quotation mark.
-
Double quotation mark ""
- Double quotation mark escape characters \ are valid. The usual applications of escape characters are \ n line feed, \ r carriage return, \ u \l case of the next letter, and so on
- And you can use $to interpolate a variable into a string
#!/usr/bin/perl use 5.014; # The single quote escape character can only be used to escape the backslash itself and the single quote print '\n just\n'; print "\n"; print 'Output a single quotation mark \',Output a backslash at\\'; print "\n"; # Double quotation marks are valid and can be used to interpolate a variable into a string my $sum = 5 + 3; print "5 + 3 = $sum \n"; print "\uhello \uworld! \n";
3.2.1 string operator
. points can be used as concatenation operators for strings, as follows
#!/usr/bin/perl print "hello " . 'world' . "/n"; # Output hello world [newline character]
The x operator can repeatedly output the same characters, as follows
The number of repetitions will be rounded off before use, and the decimal places will be removed. When the number of repetitions is less than or equal to 0, an empty string will be generated
#!/usr/bin/perl print "perl " x 3; #Output perl perl perl print "perl " x 2.8; #Output perl perl print "perl " x 0; #Output [empty string]
The two can be used in combination, for example
#!/usr/bin/perl print "perl " x 3 . "\n"; #Output Perl [line break]
3.2.2 string comparison operator
Six comparison operations are also supported, but the symbols are different from numbers.
Character comparison operation | Operator | Example | Example operation results |
---|---|---|---|
equal | eq | "a" eq "a" | really |
Unequal | ne | "35" ne "35.0" | True, compare by character |
less than | lt | "b" lt "a" | Really, in alphabetical order |
greater than | gt | "aa" gt "a" | True, according to character length |
Less than or equal to | le | "aa" le "aa" | really |
Greater than or equal to | ge | "aa" ge "aa" | really |
3.2.3 function operation of string
-
index lookup substring
Basic format: index($STRING, matchString, [start_index])
- $STRING required: the target STRING to find
- matchString required: the character to find
- start_index is not required: find the match from the subscript of the target string
Find the relative position of the specified string in the target string, and return the matched subscript value. If not, return - 1
#!/usr/bin/perl my $stuff = "hello world"; my $where = index $stuff, "world"; # $where = 6 my $where1 = index $stuff, "l"; # $where1 = 2 my $where2 = index $stuff, "l", $where1 + 1; # $where2 = 3 my $where3 = index $stuff, "l", $where2 + 1; # $where3 = 9 my $where4 = index $stuff, "l", $where3 + 1; # $where4 = -1
-
substr intercept string
Basic format: substr($STRING, start_index, [sub_length])
- $STRING required: target character
- start_index required: the subscript of the string to be intercepted
- sub_length is not required: intercept length
The target string will not change after being intercepted
#!/usr/bin/perl use 5.010; my $str = "I solemnly swear that I am up to no good" my $ret1 = substr $str, 20; # $ret1 = I am up to no good say $ret1 . "\n" . $str; # $str is still equal to the original text my $ret2 = substr $str, -4, 4; # $ret2 = good say $ret2 . "\n" . $str; # $str is still equal to the original text
-
printf and sprintf format strings
Basic format: printf(pattern, $String...)
- pattern required: format statement. Characters starting with% correspond to a format. At the same time, a parameter will be formatted
- $String... Required: there may be multiple target characters to format, corresponding to the number of pattern formatting statements
Basic format: sprintf(pattern, $String...)
printf has the same parameters and handles as sprintf. printf will directly print the formatted characters to the command line, while sprintf will return the formatted characters without printing
printf is basically consistent with the formatted output of java and C.
#!/usr/bin/perl # %g means to automatically select floating point number, integer or exponential form as required # 2.5 3 1.0683e+29 printf "%g %g %g\n", 5/2, 51/17, 51**17; # %d represents decimal integer format, and the number after the decimal point will be automatically removed # 2 printf "%d\n", 2.5; # %6d 6 indicates a fixed length character, which is frequently used when outputting messages such as logs # ······2 (· indicates space) printf "%6d\n", 2;
3.2.4 automatic operation and type conversion of numbers and strings
The operation operator determines the combination product of numbers and strings. If the number operator is used to connect, all connected variables will be regarded as numbers, and if the character operator is used to connect, the connected variables will be regarded as characters, as shown below
#!/usr/bin/perl use 5.014; say "1" + 2; #Output 3 say "1" . 2; #Output 12 say "1" x 3 + 2; #Output 113 repeated characters, run first say "1" . 3 + 2; #Output 15 addition runs first say "1" x 3 * 2; #Output 222 repeat character times run first say "1" . 3 * 2; #Output 16 multiplication runs first
Note:
-
Operator priority, refer to the documentation, and common ones are shown on the right: () higher than + + – higher than * /% x higher than + -
-
Automatic character to number conversion rule. If the first character is not a number, it will be regarded as 0. Otherwise, it will take a number until it matches a character that is not a number. For example:
-
12kjsdha2321 will be treated as the number 12.
-
lksjdlak123 will be treated as the number 0.
Code demonstration
#!/usr/bin/perl use 5.014; say "ksjdhalkd23" * 12; # Output 0 say "12ioqwnk3354" * 2; # Output 24
3.3 Boolean
Perl does not have two explicit scalar values to define true and false
The definition of true and false is defined as false. The following values are false values. In addition, other values are true values
- undef - indicates an undefined value
- 0 - the number 0, even if you write 000 or 0.0
- '' - empty string
- '0' - a string containing only one 0 character
The following example
#!/usr/bin/perl use 5.014; # 0 is false if(!0) { say "hello"; } # Null character is false if(!"") { say "world"; } # Any non empty character is true if('asdjkhasdk') { say "anyway"; } # Any number other than 0 is true if(5646545) { say "everything is ok"; } # undef is false if(undef == 0) { say "undefined == false " }
3.4 variables
It refers to the container for storing values, which is the same as variables in other programming languages.
Declare a variable with $
Naming is case sensitive, letters or underscores_ The beginning can be composed of upper and lower case letters, numbers and underscores.
#!/usr/bin/perl $variable1 = 1; #Declare a numeric variable $usr_variable = 1; #Variables that use underscores to connect multiple words $usrVariable = 1; #Use hump nomenclature $USER_VARIBALE_CONSTANT = 1; #!!! It is not recommended to use all uppercase, which may conflict with the special variable names reserved by Perl
3.4.1 assignment of variables
Use the = sign to connect variables and scalars to complete the assignment
#!/usr/bin/perl $variable = "value";
The operators of character variables and numeric variables are the same as scalars. In addition, binocular assignment operators are supported
As shown below
#!/usr/bin/perl use 5.014; # Add equals operation my $num1; $num1 = $num1 + 1; $num1 += 1; say $num1; # Output 2 0 + 1 + 1 = 2 # Minus equals operation my $num2; $num2 = $num2 - 1; $num2 -= 1; say $num2; # Output - 2 0 - 1 - 1 = - 2 # Multiply equal operation my $num3 = 1; $num3 = $num3 * 2; $num3 *= 2; say $num3; # Output 4 1 * 2 * 2 = 4 # Division equals operation my $num4 = 1; $num4 = $num4 / 2; $num4 /= 2; say $num4; # Output 1 / 2 / 2 = 0.25; # . equals operation (concatenation character) my $str1 = "one_"; $str1 = $str1 . "two_"; $str1 .= "three"; say $str1; # Output one_two_three; # x equals operation (number of repetitions of string) my $str2 = "yo "; $str2 = $str2 x 2; $str2 x= 2; say $str2; # Output Yo Yo Yo;
3.4.2 scope of variable
Reprinted from https://blog.csdn.net/henjay724/article/details/8457556#
Considering that the example can not fully reflect the main functions and differences of keywords, the example part of the reprinted content is modified
Due to some errors in the original text, changes have also been made here. For example, local cannot declare a new variable, which can be deleted after experiments. In addition, some contents have been added to supplement.
Summary of knowledge points:
-
Variable ranges are divided into two categories: global and local
-
Global variable standard (our) keyword, local private variable (my) keyword
-
Local variable (local) keyword, persistent private variable (state) keyword
In Perl, all variables, subroutines and other entities that can be named have package scope (also known as "global scope") by default, that is, they exist in the symbol table of the current package. You can declare the package name in the script file through the package function
package myPack;
If the package name is not declared, the default is the main package.
If there is no keyword to declare variables, Perl will default to global variables. However, if the use strict directive is enabled, Perl will force that variables must be declared before they can be used.
1. Package domain global our
our operator is used to explicitly create package scope variables.
#!/usr/bin/perl use 5.010; # Keyword our sub subroutine1{ say $var; #Get the global var variable $var +=1; say $var; &subroutine2; } sub subroutine2{ $var +=1; #Get the global var variable say $var; } our $var =1; #Global, scope package &subroutine1; #Output 1 \ N 2 \ n 3 \ n say $var; #Output 3\n
Note 1: our operator was introduced in the era of Perl 5. Variables in the era of Perl 4 are global and do not need to be declared. In the Perl 5 era, in order to avoid variable confusion, the use strict instruction was introduced to enforce that variables must be declared, and our operator defines a global variable that looks like a lexical scope, which is restricted by the strict instruction.
Note 2: if the global variable already exists, our function is to declare the global variable (similar to extern in C).
2. Temporary global local
Local modifies a variable so that it is valid in the subroutine domain as a local variable. Unlike my, it can continue to be passed to other subroutines called inside the subroutine to produce a passing effect.
#!/usr/bin/perl use 5.010; # Keyword local sub subroutine0{ my $var = 100; #Declare the local var variable, and print the local variable say $var; &subroutine1; } sub subroutine1{ say $var; #As a private variable, the my variable cannot be passed to the subroutine it calls. At this time, the global variable is obtained local $var = 5; #Temporary global variable, the scope is within the subroutine say $var; &subroutine2; } sub subroutine2{ $var +=1; #The local variable will continue to be passed inside the subroutine it calls say $var; } our $var =1; #Global, scope package &subroutine0; #Output 100 \ n 1 \ N 5 \ n 6 \ n say $var; #Output 1\n
Note 1: the local variable works at runtime. It will save the parameter value in a run stack. When the execution thread leaves the scope, the variables temporarily stored in the original scope will be restored.
Note 2:local and my only take effect within a restricted block of code, but local variables can continue to exist in the subroutine called in this code block.
3. Private ownership
Although the local operator has a long history than the my operator, Perl later added my to share the work of local. In most cases, my should be preferred, but local must be used in some special cases.
The my operator is used to create lexical scope variables. The variables created by my survive at the beginning of the declaration until the end of the closed scope.
A closed scope can be a region in a pair of curly braces, a file, or an eval string.
#!/usr/bin/perl use 5.010; # Keyword my our $var =1; #Global variable with scope package sub subroutine0{ my $var =2; #Private local variable with curly braces scope $var +=1; say $var; &subroutine1; } sub subroutine1{ say $var; #my private variable cannot be passed to the subroutine it calls, but the global variable is still read } &subroutine0; #Output 3 \ n 1 \ n say $var; #Output 1\n
Note 1: my is a new variable created in the private symbol table during compilation. This variable cannot be accessed independently by name at runtime, that is, it does not exist in the package symbol table (non global).
Note 2: when the my variable in the closed scope has the same name as the outer variable, the current my variable is valid. When exiting the scope, the outer variable value remains unchanged.
4. Persistent local state
Using the state operator to declare a variable can retain the value before the variable during multiple calls of the subroutine, and limit the scope of the variable to the subroutine.
#!/usr/bin/perl use 5.010; # Keyword state sub subroutine0 { state $var =2; #Persistent local variable, the scope is within the subroutine $var += 1; say $var; &subroutine1; } sub subroutine1 { say $var; #Since neither the state variable nor the my variable can be passed, an empty string is output here } my $var = 1; #Local variable, scope, current script file &subroutine0; #Output 3\n empty string \ n &subroutine0; #Output 4\n empty string \ n #Here, output 4 indicates the value of the last operation of state in its scope to save say $var; #Output 1\n
Note 1: the variable modified by state will become invalid after exiting the subroutine. It should be understood that the meaning of retaining the value before the variable during multiple calls is limited to the scope.
Note 2: state was introduced from Perl 5.10, so use 5.010 or later must be added before use.
Note 3: state can declare scalar, array and hash. However, arrays and hashes cannot be initialized when declared (at least not supported by Perl 5.14).
3.5 lists and arrays
- A list refers to an ordered collection of multiple values, and an array corresponds to a variable that stores a list
3.5.1 array
Arrays are variables that store lists. Each array contains a list.
Basic format: arrays [0] = 1$ element = arrays[0]; $ element = arrays[-1];
-
How to declare an array $NAME[index] = value
outline
-
The array subscript points to a scalar to complete the declaration
-
The element with subscript 0 is the first element of the array
-
If the declared array subscript points to a number greater than 0, all elements between it and the first element will be automatically expanded. The expanded element is undef by default
#!/usr/bin/perl $arr1[0] = 1; #Declare an array arr1 and assign a value to its first element $arr1[1.564] = 2; #Automatic decimal point removal is equivalent to $arr1[1] = 2; $arr222[99] = 100;#Declare an array arr222 and assign a value to its 100th element, and the values of the other 99 elements are undef
-
-
How to get the elements of an array N A M E [ i n d e x ] ∗ ∗ or person ∗ ∗ NAME[index] * * or** NAME[index] * * or * * negative number of NAME[index]
outline
- $array subscript gets an array element
- If the array index does not exist, an undef is returned
- You can take a negative number as the subscript value, that is, the reciprocal of the subscript, starting from - 1
#!/usr/bin/perl use 5.010; $arr[0] = 'a'; $arr[1] = undef; $arr[2] = "b"; my $value = $arr[0]; #Get the first element 'a' of the array my $value = $arr[999999]; #If the maximum length of the array subscript is exceeded, no error will be caused, but an undef value will be obtained my $value = $arr[$#arr];#Get the last element of the array "b" my $value = $arr[-1]; #Get the last element of the array "b" my $value = $arr[-2]; #Get the penultimate element undef of the array my $value = $arr[-3]; #Get the penultimate element of the array, that is, the first element 'a' my $value = $arr[-4]; #Exceeded the index of the array to get the undef value
-
How to get the length of an array
outline
- $#ARRAYS_ Name (subscript of the last element of the array) + 1
#!/usr/bin/perl $arr[9] = 10; my $len = $#arr + 1; # $#arr = 9, 9 + 1 equals 10; $arr[$#arr] = 10; # Therefore, the last value of the array can be obtained by modifying it in this form, but it should be declared on the premise that the array is declared, otherwise an error will be caused
3.5.2 list
A list that represents a list of data in a program. Its relationship with arrays is the same as that between ratios and variables, one as data and one as a container or reference for storing data.
-
How to represent a list?
#!/usr/bin/perl (1, 2, 3) # A list of three numeric elements (1.25, "str") # A list of two elements ($var1, $var2) # Variables can also be stored in the list (1..100) # You can use A linked number that represents a hundred numbers containing 1 - 100 qw(windows linux ubuntu) #Shorthand for quoted world, equivalent to ('windows', 'linxu', 'ubuntu'), is a shorthand way to quickly declare a character list. Note that it declares characters in single quotation marks, so it does not support character escape qw|(ios) (andorid) (harmonyOS)| #Another qw abbreviation, qw abbreviation, can use different symbols as delimiters. For specific reasons, such as the writing method in this example, because the text itself has parentheses, it can not be separated correctly by using parentheses. This example is equivalent to ('(ios)', '(andorid)', '(harmonyOS)' qw<1 2 3> #In qw abbreviation, delimiters can also use other well-defined left and right symbols, such as {} < > () []. This example is equivalent to ('1 ',' 2 ',' 3 ')
-
How to assign a list to a variable \ array?
@Array name, which will represent the whole array, as follows, assuming that the array has only three elements with subscripts 0 - 2
for e l e m e n t ( element ( element(arr[0], $arr[1], $arr[2]) {} is equivalent to for $element (@arr) {}
#!/usr/bin/perl ($var1, $var2, $var3) = (1, 2, 3, 4, 5); # The list can be directly assigned to variables, which is equivalent to assigning values to three variables respectively. Redundant elements will be ignored. If the parameters are insufficient, the undef value will be given ($var1, $var2) = ($var2, $var1); # A method of quickly exchanging two variable values in perl ($arr[0],$arr[1],$arr[2]) = qw[Lion spotted hyena leopard wild dog cheetah Jackal]; # Assign values to the elements of the array subscript 0 - 2, and the extra two characters will be ignored @arr = ('lion', 'Spotted hyena', 'leopard', 'Wild dog', 'Cheetah', 'jackal'); # Assign the elements in the list to the array, starting with the subscript 0 @arr = qw[Lion spotted hyena leopard wild dog cheetah Jackal]; # Assign the elements in the list to the array, starting with the subscript 0. Here we compare the above two examples to see the use of qw abbreviation and @ symbol @copy = @arr; # Copy an array
3.5.3 array and Stack
Stack pop push operation
Perl's array supports Stack operation. The Stack structure can be simply understood as a first in then out list. The in operation is called push and the out operation is called pop.
#!/usr/bin/perl use 5.010; @arr = 1..10; say $#arr + 1; # 10 @var = pop(@arr); #Stack out operation 1 say $#arr + 1; # 9 $val = pop @arr; #Stack out operation 2 say $#arr + 1; # 8 pop @arr; # Out of stack data may not be used say $#arr + 1; # 7 push(@arr, 11); #Stack operation 1 say $#arr + 1; # 8 push @arr, 12; #Stack operation 2 say $#arr + 1; # 9 push @arr, 13..20; #Batch digital stacking say $#arr + 1; # 17 push @arr, qw[a b c d]; #Batch character stacking say $#arr + 1; # 21 @newarr = 'a'..'z'; push @arr, @newarr; #Batch stack of data from other arrays say $#arr + 1; # 47 for $var (@arr) { print $var . " "; } say;
Stack shift and unshift operations
pop and push refer to the elements at the end of the array, while shift and unshift refer to the elements at the head of the array. The usage is the same and there is no explanation
#!/usr/bin/perl @arr = 1..10; $var = shift @arr; unshift @arr, 'newElement';
splice transfer operation
Basic format ([] indicates optional parameters): [@ RECEIVE_ARR] = splice @ARR_NAME start_index [splice_number] [replace_list]
Explain each parameter separately
- @RECEIVE_ARR optional: the splice operation returns an array, that is, the removed part of the source array, @ RECEIVE_ARR is used to receive the return value
- splice required: operator itself
- @ARR_NAME required: source array itself
- start_index required: remove the subscript at the beginning of the operation
- splice_number optional: the number of elements to be removed. The default is $#arr_ Name (last element of array) - start_index + 1;
- replace_list optional: after the removal operation, add the list to the source array, which can be another array or a list direct quantity
The code example is as follows
#!/usr/bin/perl use 5.010; @arr = 'a'..'z'; # a - z 26 letters @removed = splice @arr, 14; #Remove all elements after subscript 14 say "first removed : @removed"; #Output the first removed element o - z @removed = splice @arr, 0, 7; #Remove 7 elements after subscript 0 say "second removed : @removed"; #Output the second removed element a - g @removed = splice @arr, 0, 7, 1..10; #Remove 7 elements after subscript 0, and then supplement 1 - 10 numeric elements say "the third time removed : @removed"; #Output the element h - n removed for the third time. Pay attention to the readjustment of the element subscript after the second removal say "current arr : @arr";
3.5.4 array interpolation of strings
Arrays can be directly interpolated into strings using the @ symbol, which is the same as the interpolation of $variables, but it also leads to restrictions on the use of @ symbols, which should be paid attention to when actually writing scripts
for example
#!/usr/bin/perl use 5.010; @arr = 1..10; $str = "countdown: @arr"; say $str; # Solving the symbol conflict between email and array interpolation $email = "11111@qq.com"; #This will be considered by perl as interpolating a qq array, wrong writing say $email; $email = '11111@qq.com'; #Use single quotation marks to limit escape. Write correctly say $email; $email = "11111\@qq.com"; #Manual escape is troublesome and correct say $email;
3.5.5 common functions of array
-
reserver inverse array
Basic format: reverse arraysOrList
- arraysOrList required: array or list direct quantity to be inverted
#!/usr/bin/perl my @numbers = 1..10; # Array with elements 1 - 10 my @countdownNumbers = reverse @numbers; # Array with element 10 - 1 my @countdownNumbers2 = reverse 1..10; # Array with element 10 - 1
-
Sort array sort
Basic format: sort arraysOrList
- arraysOrList required: the array or list quantity to be sorted
Sort elements according to the internal character encoding order
#!/usr/bin/perl use 5.010; @words = qw [b a g c d f e]; # Disordered letter @sortedWords1 = sort @words; # Sorted a b c d e f g @sortedWords2 = sort qw /b a g c d f e/; # The effect is the same as the above example say "@words\n@sortedWords1\n@sortedWords2";
-
each array traversal
Basic format: ($index, $value) = each @array
- $index required: current element subscript
- $value required: current element value
- @Array required: traversal array
each array will return a set of key value pairs. The key is the subscript of the array element and the value is the value of the array element.
In fact, with foreach, each is not so easy to use. Unless you need some programming for array subscripts, it may be more convenient to use foreach
each syntax needs to be supported by versions above 5.012
#!/usr/bin/perl use 5.012; my @fruits = reverse sort qw <banana orange watermelon apple>; # Use the each function to traverse the array while (my($index, $value) = each @fruits) { say "current element = $index:$value"; } # Traverses the array using the array subscript foreach foreach my $index (0.. $#fruits) { say "current element = $index:$fruits[$index]"; } # Use the for loop to traverse the array for(my $index = 0; $index <= $#fruits; $index += 1) { say "current element = $index:$fruits[$index]"; }
4 control structure of Perl
Include the following
- Judgment control structure (if[else], unless[else])
- Loop control structure (while, until, forEach, for)
- Loop control operator (last next redo)
- Label usage of loop body (LABEL)
4.1 judgment structure
4.1.1 If and unless
Unless is anti if, but compared with if, unless is not only a little anti human in semantics, but also lacks elsif multiple judgment support. Therefore, if is generally used.
Code example
#!/usr/bin/perl use 5.014; #Use if judgment foreach (1..10) { my $value = (int rand 10); # Generate a random integer of 0 - 9 if ($value == 0) { # When the condition is true, enter the code block say "$value"; } elsif($value % 2 == 0) { say "$value Is a non-zero even number"; } else { say "$value It's an odd number"; } } say "-------------Dividing line-------------"; #Use unless judgment foreach(1..10) { my $value = (int rand 10); unless ($value % 2 == 0) { # When the condition is false, enter the code block say "$value It's an odd number"; } else { say "$value It's an even number"; } }
4.2 circulation structure
4.2.1 while and until
In the while statement, when the condition is true, the code block is executed circularly,
On the contrary, both are semantically consistent with the understanding of human language, so it is possible to use either.
When the condition is true, the code block will be executed continuously, and the following example will print 2 4 6 8 10 twice in turn
#!/usr/bin/perl $count = 0; while($count < 10) { #When count is less than 10 $count += 2; print "$count\n"; } print "-------------Dividing line-------------\n"; $count = 0; until($count >= 10) { #Until count > = 10 $count += 2; print "$count\n"; }
4.2.3 foreach and for
for and foreach can be mixed to a large extent. You can choose your favorite writing method in the actual programming process
For the traversal operation of array variables or lists, the following three examples will print 1 - 10 at a time
#!/usr/bin/perl @number = 0; @numbers = 1..3; foreach $number (@numbers) { print "$number\n"; } for $number (@numbers) { print "$number\n"; } for $number (1..3) { print "$number\n"; } for (qw[1 2 3]) { print "$_\n"; #Note that there is no control variable in this example, but $_, This is the default variable for perl. This kind of writing is also allowed } use 5.010; for (qw[google apache microsoft]) { say; #This is equivalent to say "$"; } for($int = 0; $int < 5; $int += 1) { say $int; }
Note:
- In the above example, number, as the control variable of foreach loop, has a value before the start of the loop, so it will return to the original value of 0 at the end of each loop.
- About $$_ It is the default variable in Perl and is used in many single parameter scenarios, including loop / judgment structures and various functions. For details, please refer to https://cn.perlmaven.com/the-default-variable-of-perl , and try to write it
5 Perl subroutine
perl also supports functions similar to C to further encapsulate the program. The basic format of the subroutine is
sub subroutine name { #The program body of the subroutine is written here }
The subroutine is called with the & symbol or by adding () after the program name
&subroutine name ; subroutine name (); # Subroutine call with parameters &subroutine name ($param1, $param2); subroutine name ($param1, $param2);
When the above subroutine contains parameters, how can the subroutine obtain these parameters? perl has no place to explicitly define subroutine parameters. At this point, you can use perl's default parameters$_
#!/usr/bin/perl use 5.010; sub mySubroutine { for $index (0..$#_) { #From 0 to$_ Last subscript of parameter say "parameter $index Value is: $_[$index]"; } # More intuitive say "First parameter = $_[0]"; say "Second parameter = $_[1]"; } mySubroutine("Hello Subroutine", 2021);
After finishing the parameters of the program, based on our previous programming experience, we can easily think of the problem of return value. How to define and receive the return value of the program? In fact, during the execution of the subroutine, the result of the last operation will be used as the return value of the subroutine. The program automatically recognizes it without explicitly using the return keyword. Of course, you can also directly use return to return a value to end the subroutine
Code example
#!/usr/bin/perl use 5.010; sub mySubroutine0 { "Hello subroutine"; } sub mySubroutine1 { } sub mySubroutine2 { return "read paramter" if @_ > 0; #If the parameter list is greater than 0, the value is returned directly "Hello subroutine"; } $ret0 = mySubroutine0(); $ret1 = mySubroutine1(); $ret2 = mySubroutine2(1); #Pass in a parameter say $ret0; # Output Hello subroutine say $ret1; # Output empty string say $ret2; # Output read paramter
More example codes are as follows:
#!/usr/bin/perl use 5.014; # Declare a subroutine with no return value sub not_ret_func { # In fact, there is a return value, and the last line of print function will return the successfully executed code 1 # This return value usually serves as a successful execution flag for most instructions # It can be used for conditional judgment in individual scenarios print "hello world \n"; } # Declare a subroutine with no return value sub has_ret_func { # The last value is the return value my $test = "return value"; $test; } # call my $ret1 = ¬_ret_func; say 'func1 return = ' . $ret1 . " func2 return = " . &has_ret_func; # Declare a subroutine with parameters sub has_param_func { # Default array parameters$_ Parameter list of the function subroutine $_[0] + $_[1]; } # Call subroutine with parameters my $num1 = 1; my $num2 = 2; say $num1 . ' + ' . $num2 . ' = ' . &has_param_func($num1, $num2);
The output is as follows
[root@localhost test]# chmod 447 sub.pl [root@localhost test]# ./sub.pl hello world func1 return = 1 func2 return = return value 1 + 2 = 3 [root@localhost test]#
``perl
#!/usr/bin/perl
use 5.010;
sub mySubroutine0 {
"Hello subroutine";
}
sub mySubroutine1 {
}
sub mySubroutine2 {
return “read paramter” if @_ > 0; # If the parameter list is greater than 0, the value is returned directly
"Hello subroutine";
}
$ret0 = mySubroutine0();
$ret1 = mySubroutine1();
$ret2 = mySubroutine2(1); # Pass in a parameter
say $ret0; # Output Hello subroutine
say $ret1; # Output empty string
say $ret2; # Output read paramter
[External chain picture transfer...(img-62W9inoS-1626155603241)] More example codes are as follows: ```perl #!/usr/bin/perl use 5.014; # Declare a subroutine with no return value sub not_ret_func { # In fact, there is a return value, and the last line of print function will return the successfully executed code 1 # This return value usually serves as a successful execution flag for most instructions # It can be used for conditional judgment in individual scenarios print "hello world \n"; } # Declare a subroutine with no return value sub has_ret_func { # The last value is the return value my $test = "return value"; $test; } # call my $ret1 = ¬_ret_func; say 'func1 return = ' . $ret1 . " func2 return = " . &has_ret_func; # Declare a subroutine with parameters sub has_param_func { # Default array parameters$_ Parameter list of the function subroutine $_[0] + $_[1]; } # Call subroutine with parameters my $num1 = 1; my $num2 = 2; say $num1 . ' + ' . $num2 . ' = ' . &has_param_func($num1, $num2);
The output is as follows
[root@localhost test]# chmod 447 sub.pl [root@localhost test]# ./sub.pl hello world func1 return = 1 func2 return = return value 1 + 2 = 3 [root@localhost test]#