one. DataType (data type ):
Perl's data types are roughly four: Scalar (variables), Scalar Array (array), hash array (hash), References (pointer), but they seem to be small but more than sufficient. In particular, you can write a Perl program without the prior declaration of variables, this is very convenient to learn the language of the program, but in order to later debugging and maintenance convenience, I suggest you or form the habit of declaring variables in advance.
1 Scalar (Pure quantity):
A scalar variable is the most basic form of data in Perl, which can represent a character, string, Integer, or even floating-point number, and Perl regards them as the same thing! You can even mix it up, it's unbelievable. For example:
# The back of the well font size begins with annotations.
# The number of scalar numbers begins with $.
# My is a way to declare a variable, it can make a variable regionalization.
# when declaring a variable, Perl uses it as a global variable without my or local.
# in practice, we enclose strings in double quotes, and values do not have to be quoted.
My $x = "abc";
my $x = 123;
my $x = 4.56;
1-1 Common operator Operators
1), Arithmetic operators
+ (plus),-(minus), * (multiply),/(except), * * (Power),% (+),-(negative)
(1) The result of exponentiation (* *) cannot exceed the range of the number. When the exponent is a decimal number, the base cannot be negative, for example: 25**1.5=125, (-25) **1.5=? (not established)
(2) The remainder (%) operand is an integer, otherwise interception is to be taken. The second number cannot be 0 (because the divisor cannot be 0)
(3) negative (-)-$a = $a * (-1)
Also, note that when a string participates in an operation and needs to be converted to an integer, the value is 0 if it cannot be converted to an integer. For example: ' 2 ' +1=3, ' a ' +1=1
2), numeric comparison operators
< (less than), = (equal To), > (greater than), = = (equals), <= (less than equal), >= (greater than equal),!= (Not Equal), <=> (Compare)
(1) = =: comparison operation, The result of the comparison is true or Non-zero, False or 0
(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 converts the operands to integers, not to integers, 0
(4) floating-point numbers are not accurate, do not compare the number of similar values, otherwise the result is unexpected
3), Comparison of the string comparison operator
Lt (less than), GT (greater than), EQ (equal To), LE (less than equal to), GE (greater than equal), NE (equals), and the CMP (comparison)
(1) String: Comparisons by alphabetical order, numbers < caps < lowercase letter (a small-Z-Large)
(2) string comparison Order: strings are compared from left to right. ' Azz ' < ' BC ' (ie: first A is compared to B, then Z is compared to c)
(3) When a string is the prefix of another, the length is large. For example: The Dog<doghouse
(4) string can be carried from right to left, and alphanumeric
(5) automatically converts the operand to a string. 123 LT => ' 123 ' lt '
(6) CMP is equivalent to <=>, the result is -1,0, 1
For example: $str 1= "A", $str 2= "A", then print ($STR 1 CMP $str 2) ==> 0
For example: $str 1= "A", $str 2= "B", Print ($STR 1 CMP $str 2) ===>-1
For example: $str 1= "B", $str 2= "a", print ($STR 1 cmp $str 2) = = > 1
(7) empty string, 0,undef, all three cases are false
for example: the results of the following comparison
!= 30+5 #false
= = = 35.0 & nbsp; #true
' eq ' 35.0 ' #false (compared as String)
' Fred ' lt ' Barney ' #false
' Fred ' L t ' free ' #false
' Fred ' eq ' Fred ' #true
' Fred ' EQ "Fred" #false
' ' gt ' #true
4), string concatenation (.), character/string repetition (x)
(1) connection (".") ), for example: $a = ' a '. B '; => ' AB '
You can write print directly $a $b=>print $a when you print. $b; But the two principles are different.
(2) Repeat ("X"), note: There are spaces before and after (purpose: to separate from the variable name), such as: ' A ' x 5= ' aaaaa ', if the repeat number of <1, then return the empty string
For example: "5" x 4, which is: "5555"
For example: "Love" x (4+1), which is: "Lovelovelovelovelove"
For example: "4.8" x 4, which is: "4.84.84.84.8"
For example: 6.1 x 3, which is: "6.16.16.1"
That is, the left is a string, and the right is the number of times the string appears
5), logical operators (&& and) (with), | | (or) (or),! (not) (non), XOR (exclusive OR)
(1) The value on the left is counted first, then the right value
(2) && and and have different priorities, but unless exceptional circumstances, it is difficult to distinguish
6), bitwise operator operator
& (Bitwise AND), | (bitwise OR), ~ (bitwise non), ^ (bitwise XOR), << (move left), >> (move right)
(1) The operand is a binary integer, and if it is a decimal, it is truncated to an integer.
(2) << left, the vacancy after the removal of 0, the value of the original number of 2*n times (for example: Z<<4, then z=z* (2 of 4))
(3) >> right, first complement 0, the value is half of the original value (and rounding) (for example: Z>>4, then z=z/(2 of the Second party))
7), assignment operator
=, + =, =, *=,/=,%=, **=, &=, |=, ^=,.
(1) $a +=1=> $a = $a +1
(2) The =3 of the $a= $b =3;=> $a can be even, $b = 3;
(3) Mixing ($a = $b) +=3;=> $a = $b; $a = $a +3; (not recommended)
8), self-increase (+ +), self-reduction (-)
(1) Do not use this operator on both sides of the variable: + + $var
(2) Do not use the variable since the increase/subtraction in the same expression again: $var 2 = $var 1 + + + + $var 1;
(3) can be used for the self increase of strings, when Z, Z, 9 o'clock carry. $a = ' Caz '; $a + +; ==> $a = ' CBA ';
(4) Can not be used for the self-reduction of strings, when $a--, by digital operation, the word Fuxian into 0 and then self-reduction
(5) If the string contains a non-alphanumeric symbol, or if the number is in the letter, the self increase is first converted to 0 and then self-increase
For example: $a = ' ab*c '; $a + +; ==> $a = 1;
For example: $a = ' ab5c '; $a + +; ==> $a = 1;
(6) Pre-$b=++ $a, $a increase the value of the first, then increase the $b= $a + +; $a first assign value and then increase itself; conversely, the same
For example: $a = 1; $b =++ $a; => $a =2, $b = 2;
For example: $a = 1; $b = $a + +; => $a =2, $b = 1;
(7) can only be used for a single variable, not the variables after the operation. Example: ($a + $b) + +
9), comma (equivalent to: write two statements on one line)
Scope of application: Use only if two statements are closely related
For example: $a +=1, $b = $a; => $a +=1; $b = $a;
For example: $a = "ab5c", print $a. " \ n ";
10, conditional operator
Conditions? True: false
(1) Three operands: first on the conditional expression operation, true when executing: the left of the operation, for false execution: the right-hand side of the operation
For example: $result = $var = = 0? 14:7;
(2) for simple conditions
(3) conditional expression used on the left of =
For example: $condvar = = 43? $var 1: $var 2 = 14;
For example: $condvar = = 43? $var 1 =: $var 2 = 14;
Third, operator priority (precedence--priority)
When there are several different operators in an expression, which is calculated first and which is calculated after
For example: $condvar = = 43? $var 1: $var 2 = 14; (first calculate the condition, then calculate the assignment)
For example: $x = $a = = $b; (first calculate the relationship, then assign the value)
Example: $x = = 0 | | $y/$x > 5; (To be counted first, then to be greater than, then to be equal to, the last to calculate the relationship or)
For example: $result = 2 + 6 * * * 2 << 2; (first exponentiation, then multiply, then add, then left, then the final assignment)
(1) The general priority is as follows: self-reduction is highest, single operand is higher than multiple operands, numeric operation > comparison operation (numeric comparison and string comparison) > bit operation > Assignment operation > Logic operation
(2) Digital operation: Power > */>+-
(3) Comparison operation: < (less than), > (Greater than) higher (= = and!=)
2 Scalar Array :
The concept of Perl array variables and lists, which is a sequence of values contained in parentheses, can be any number or NULL, and the list is stored in a Perl array variable, unlike a simple variable, the Perl array variable begins with the character "@".
Perl Array Variables and lists
One, List
A list is a sequence of values enclosed in parentheses that can be any number or NULL, such as:
(1,5.3, "Hello", 2), empty list: ().
Note: A list containing only one numeric value (for example: (43.2)) is different from the value itself (that is, 43.2), but they can be
To convert or assign to each other.
List example:
($var, "astring")
(17,26<<2)
($var 1+ $var 2)
($value, "Theansweris$value")
Perl Arrays--Storage of lists
The list is stored in a Perl array variable, and unlike a simple variable, the PERL array variable starts with the character "@", such as:
@array = (1,2,3);
Note:
(1) A Perl array variable is created with an empty initial value: ().
(2) Because Perl uses @ and $ to differentiate between Perl array variables and simple variables, the same name can be used for Perl
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 by subscript, and the first element is labeled 0. An attempt was made to access a nonexistent Perl array element
, the result is null, but if you assign a value to an element that is larger than the size of the Perl array, the Perl array grows automatically, the original
The element value that is not here is null. Such as:
@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;
Assigning values to a list with a Perl array
@list1 = (2,3,4);
@list2 = (1, @list1, 5); # @list2 = (1,2,3,4,5)
The assignment of a Perl array to a simple variable
(1) @array = (5,7,11);
($var 1, $var 2) = @array; # $var 1=5, $var 2=7,11 ignored
(2) @array = (5,7);
($var 1, $var 2, $var 3) = @array; # $var 1=5, $var 2=7, $var 3= "" (null)
Assign values to variables from standard input (STDIN)
$var =<stdin>;
@array =<stdin>;#^d the symbol for the end input
2, square brackets and variable substitution in the string
"$var [0]" is the first element of the Perl array @var.
' $var \[0] ' escapes the character ' [', which is equivalent to $var. ' [0], $var replaced by the variable, [0] remains unchanged.
"${var}[0]" is also equivalent to "$var". [0] ".
"$\{var}" cancels the curly braces variable substitution function, contains the text: ${var}.
3, List scope:
(1..10) = (1,2,3,4,5,6,7,8,9,10)
(2,5..7,11) = (2,5,6,7,11)
(3..3) = (3)
For real numbers
(2.1..5.3) = (2.1,3.1,4.1,5.1)
(4.5..1.6) = ()
For strings
("AAA" ...) AAD ") = (" AAA "," AaB "," AAC "," AAD ")
@day_of_month = ("01" ...) 31 ")
Can contain a variable or an expression
($var 1. $var 2+5)
Small tips:
$fred = "Fred";
Print ("Hello,". $fred. "! \ n ") x2);
The results are:
hello,fred!
hello,fred!
4, the output of the Perl array:
(1) @array = (1,2,3);
Print (@array, "\ n");
The results are:
123
(2) @array = (1,2,3);
Print ("@array \ n");
The results are:
123
5, List/perl the length of the 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 the @array
($scalar) = @array; # $scalar = 1, that is, @array the value of the first element
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, the Child 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", +); # @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
You can exchange elements in the form of a child Perl array:
@array [1,2]= @array [2,1];
7. Library functions for Perl arrays
(1) sort--sorted 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 to tail
The meaning of the chop is to remove the last character, the line break, when the stdin (keyboard) input string is entered. And if it works on a Perl array, do so with every element of the Perl array.
@list = ("Rabbit", "12345", "quartz");
Chop (@list); # @list = ("Rabbi", "1234", "quart") now
(4) join/split--connection/Split
The first parameter of the join is the intermediate character used for the connection, and the remainder is the Perl array of characters to be concatenated.
$string =join ("", "This", "is", "a", "string"); #结果为 "Thisisastring"
@list = ("Words", "and");
$string =join ("::", @list, "colons"); #结果为 "Words::and::colons"
@array =split (/::/, $string); # @array = ("Words", "and", "colons") now
3 Hash Array (associative array) :
Perl Hash common usage
Basic usage
# initialization%h is an empty array%h = {};# is initialized with an array%h as a=>1, b=>2%h = (' A ', 1, ' B ', 2); # The meaning is the same, just another more figurative way of writing. %h = (' A ' =>1, ' B ' =>2); #如果key是字符串, you can omit the quotation marks. The following line is the same as the line above%h = (a=>1, b=>2); # use {} to access print ' $h {a}\n '; # print 1$h{b} = ' 2b ';p rint ' $h {b}\n '; # Print 2b# Delete key with Deletedelete $h {b}; # remove ' B ' from $h
Empty hash
Undef%h
Get all the key values of the hash
# Get all keys, order depends on hash function, or random sequence
@all_keys = Keys%h;
# All key values are sorted by hash value from large to small. Comparisons of values are numeric comparisons (e.g., 10>9)
@all_keys = sort{$h {$b}<=> $h {$a}} (keys%h);
# All key values are sorted by hash value from small to large. Comparison of values is a numeric comparison
@all_keys = sort{$h {$a}<=> $h {$b}} (keys%h);
# All key values are sorted by hash value from small to large. Comparison of values is a string comparison (for example, ' < ' 9 ')
@all_keys = sort{$h {$a} cmp $h {$b}} (keys%h);
Determine if the hash contains key
Exists ($h {$key});
Length of Hash
Want to know how much data a hash holds
$hash _size = Keys%h
# put the length of the%h in the $hash_size
Print scalar kes%h, "\ n"
# Print the length of the%h. Here we use the scalar to return the array length.
Traversing a hash
while (I ($k, $v) = each%h) {print $k---> $v \ n]
Reference reference
Reference a pointer similar to C + +
$h _ref = \%h;
# Get a hash of Reference%ahash =%{$h _ref};
# take hash reference as hash with $value = $h _ref->{akey}
# This is the same as%h{akey}
Passing Hash to function
is generally passed a reference to a function
%h = (); $h {a}=1;foo (\%h) print $h {b}, "\ n";
# Print out 2.
This value comes from function foo () sub Foo {my ($h) = @_;print $h->{a}, "\ n";
# print out 1$h->{b} = 2;}
function returns hash, or hash reference (hash reference)
function can return hash
Sub Foo {my%fh $fh {a} = 1;return%h}, my%h = foo ();p rint
two Control Structure (statements)
1 Select if structure
Perl's conditional control narrative is very much like the C language, allowing users to master it quickly. But Perl has some more practical syntax than C, and I use the bottom line to mark it out.
# Expression is a conditional narrative, Perl and C do not define Boolean data types (Boolean datatype),
# so 0 is false, not 0 is ture. Also note that the string operator and the numeric operator should be well divided.
# Code Segment is a bunch of instructions enclosed in curly 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 the directive (statement) is only one, we can use flip-syntax, which looks simpler.
Statement if (Expression);
# unless is if not
statement unless (Expression), for example:
Print "hello!\n" if ($name eq "friend");
$x-=10 if ($x = = 100);
Watch it! C language has most of Perl, and people who have learned C can learn perl effortlessly.
2 Loop Structure
Perl's loop-control narrative is similar to the C language, and of course Perl has a few more practical syntax:
# Note: The number of pure quantitative before adding a $ font, this is not the same as C language Oh.
For ($i =0 $i <=10; $i + +) {Code Segment}
# foreach is a Unix-shell script,
# The first argument is a scalar variable, and the second argument is enclosed in parentheses, which is an array of pure quantities,
# as the name suggests it is to pass each element in the array to the first argument, until all is passed.
# It and for ($i =0; $i <=$ #array; $i + +) usage is different, but the goal is to take each element of the array out.
foreach $i (@array) {Code Segment}
# in Perl, for and foreach can be mixed, just look at a person's habits.
# The following line is equal to the first narrative above, but more concise, we can try to use to see.
For $i (0..10) {Code Segment}
# while control loops and back loops.
while ($i <=10) {Code Segment}
do {Code Segment} while (Expression);
# Perl also has the same instructions as the C-language break and continue, which Perl calls it to do last and next (more colloquial).
# Last is jumping out of the loop now, next is skipping the following instructions to execute the next loop directly.
while (chomp ($i =)) {
Next if ($i = = 5);
Last unless ($i > 10);
}
Perl also has the syntax to provide label (tag), which is the goto instruction, but experienced programer do not like to use it, and I do not recommend that you use it, so press it. Those who are interested are kindly consulted. It's also worth noting that Perl does not offer a switch narrative like C, but Perl's pattern match is very powerful, so I suggest you do it directly with the if else narration.
3 Sub Programs (subroutines)
(a) syntax:sub NAME {Code}
(b) Call subroutine: &name (para1, Para2,...)
(c) Parameter transfer: @_
Perl and C are the same as call by value, but since Perl does not have to declare variables in advance, there is no need to declare what parameters to pass when creating subroutines. When the main program passes arguments to the subroutine, Perl puts the parentheses in the order of the arguments in a special global variable @_ array, and then the subroutine is free to use the arguments in the array @_, for example $_[0] is the first argument, $_[1 is the second, or $a 2,$ with my ($a 1, A3,...) = @_ to take out each parameter, of course my @arg =@_; or my%arg=@_; is also possible. Because Perl's syntax is so lively that it is particularly tricky to maintain, writing annotations becomes an important task. I suggest that you should precede each subroutine with a description of the scripts, especially the parameters that need to be passed to indicate clearly.
(d) Variable localization:my or Local
Normally, the variables we define in the program are all domain variables, so in a subroutine, you add my or local keywords, such as my $x = 3; If the subroutine uses a variable name that is not careful and the master is the same, Perl takes precedence over the variables in the currently executing subroutine.
4 I/O and file processing
(a) Syntax:
Open (FileHandle, "Expression");
Close (FileHandle);
The expression here is a narration plus a file name, and if expression only the file name is not added to the description, the preset is read-only. Expressions is 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's C ' Sfdopen for reading.
Open (FH, ">&=n") Where N is a number, this performs the equivalent's C ' Sfdopen for writing.
Cases:
# open $filename This file, if open failure then print out the message behind the die, and end the program.
Open (FILE, $filename) | | Die "Can ' t Open file $filename: $!\n";
# The following is a very concise notation, and while ($_=) {print ' $_ ';} is equivalent.
print while ();
# After opening the file to remember to close, this is the good habit of writing programs.
Close (FILE);
# $! and $_ are all special variables of Perl, as described below.
(b) Input:
Perl has no particular function to enter, because Perl automatically turns on the standard input device when it executes the program, and its filehandle is set to stdin, so the way to enter data in Perl is to use:
# Perl does not automatically remove the end of the CR/LF, unlike the C language, so use the Chomp function to help you remove it.
# People often forget this action, resulting in a different result than you think, to pay special attention to.
$input =<stdin>; Chomp $input;
# The following is a more concise wording.
Chomp ($input =<stdin>);
(c) Output:print "variables or string";
Perl also has the printf () function, the syntax is the same as the C language, I do not introduce more. Perl has another print function that is more convenient and useful than printf (), and you can't put it down. Output is nothing more than to the screen or file, with examples to illustrate the easier to understand.
# without specifying the data type of the variable, is it more convenient than printf ()?
Print "Scalar value is $x \ n";
# . Is the operator of the string addition, and the two rows are equivalent.
Print "Scalar value is". $x. "\ n";
# The method of outputting to the file.
Print file "Print $x to a FILE.";
# The following is a special use of print, learned from the use of shell script:
Print<xxx
This is called here document,xxx can be any identifier you take, the word between the identifiers will be printed as you write, like the label. And when the beginning of a line is XXX you take this identifier, it will stop the output.
Xxx
Perl also has special characters that start with "\" like C:
\t tab
\n newline
\r ret Urn
\f form feed
\b backspace
\a alarm (Bell)
\e& nbsp; Escape
\033 octalchar
\x1b hex char
\c[ control char
\l & nbsp; 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 also needs to be explained that Perl blends the usage of Unix shell script, the strings enclosed in double quotes ("") are expanded first, but the characters that follow the backslash (\) are not expanded and are treated as normal characters. Strings enclosed in single quotes (') are not expanded at all, and strings enclosed in inverted single quotes (') are executed as command-column directives, equal to system (). Beginners often confuse, but after the habit will feel not so clear on the contrary, 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
Through the & call.
2. Perl parameters
Perl naturally supports a variable number of parameters.
Inside the function, all the arguments are placed sequentially in the array @_, inside the function, $_[0] represents the function's first
arguments, and the rest.
3. Shift
Shift is followed by a number that represents the return of the first value of the array. The array is also changed, and its first element is bounced
Out
Demo Code one (max value):
#!/usr/bin/perl-w
Use strict;
# call Function Max, get the maximum value of a set of values, and output.
My $maxCnt = &max (11,22,33);
print "maxcnt= $maxCnt \ n";
Sub Max {
# using traversal algorithm. The first value in the parameter is first assigned to $CURRENTMAXCNT.
# @_ is the default array that contains all the parameters of this function [such as (11,22,33)].
# shift @_ has two results: 1. Returns the first value in the array @_ as the return value (assigned to the
$CURRENTMAXCNT). 2. The first value of the @_ array is ejected [the value of the @_ is changed to (22,33)].
My $currentMaxCnt = Shift @_;
# The @_ can be omitted when using shift in the # function. The code above can also be written like this.
# my $currentMaxCnt = shift;
# Iterate through the entire @_ array.
foreach (@_) {
# $_ represents the element in the array @_ that is currently being traversed.
if ($_ > $currentMaxCnt) {
# If you find that the current array element is larger than $currentmaxcnt, then reassign the $currentmaxcnt to the current
Elements.
$currentMaxCnt = $_;
}
}
# function return value is scalar $currentmaxcnt.
return $currentMaxCnt;
}
Demo code two (sum):
#!/usr/bin/perl-w
Use strict;
# ask for a set of numbers and print.
My $s 1 = &sumvar (11,22,33);
My $s 2 = &sumarg (22,33,44);
My $s 3 = &sumgod (11,22,33,44,55);
Print "s1= $s 1, s2= $s 2, s3= $s 3\n";
# method 1
Sub Sumvar {
# assigns the first three element values of the parameter array to ($first, $second, $third)
(My $first, my $second, my $third) = @_;
# returns its and values. Disadvantage: If you are seeking four parameters, you can still give the first three.
Return $first + $second + $third;
}
# method 2
Sub Sumarg {
# $_[0] Represents the first element of a parameter array @_. The rest of the analogy.
My $first = $_[0];
My $second = $_[1];
My $third = $_[2];
# returns its and values. Disadvantages: Same Sumvar. Just learn $_[0 by this use.
Return $first + $second + $third;
}
# Method 3, the parameters can be as many as possible. Can ask for it and.
Sub sumgod{
My $s = shift @_;
foreach (@_) {
$s = $s + $_;
}
# with the front function max.
return $s;
}
8 Summary
It is very basic to sort out some of the symbols, usages, functions, libraries and so on that I think I use more.
, but "memorize", is very helpful to improve efficiency.
Data manipulation
* $-declaration and reference with a scalar variable
* @-Declares and references a list, but when accessing a member of a list, use $listname[index]
*%-declare and reference a hash table, but when accessing a hash member, you need to use the $hashname
{Key}
Special variables
* $-file name of the currently running script
* @ARGV-List of command line arguments for the currently running script
* $_-default variable, such as current variable in loop
* @_-Function input parameter list
*%ENV-System environment variables
* @INC-perl List of include paths, we can add our own directory to the list to facilitate the introduction
Using a custom Library
* $! -Current system prompt, error message
* $^o-the name of the operating system
* Stdin,stdout,stderr-The default handle for input and output, which can be customized
* =>-When declaring a hash, it can be used to express the corresponding relationship of Key=>value
* $^i-Specifies the suffix name of the file to be backed up, so that the modified file will automatically save the suffix name with a vice
This
Special usage
* &sub-Call a function, although Perl some rules allow you to omit the & symbol here at some point, but
Is in the consistency consideration, so custom functions are called, and I'm all used to this approach.
* $#-is used to obtain the maximum index of the modulus array, in general, can also use-one to represent the last element
The index of
* QW ()-quickly declare an array of strings that can omit those annoying quotes
Regular expressions
* $-Gets the match captured by parentheses
* $ ', $&, $ '-get the matching string, and the two parts before and after it
* ^,$-the position of the string, used for positioning
Common functions
* Pop, Push, shift, unshift, reverse-list action function
* Keys,values, exists, each, delete-hash operation function
* Chomp, Split, join, index, substr, sort-string manipulation function
* sprintf,printf, print-format output function
* System, EXEC, '-Systems Command Call function
* Glob, unlink, mkdir, RmDir, Rename,chmod,chown, open, close, Opendir,
Closedir-File system operation function
* Stat, Lstat,localtime,gmtime,utime-document properties, time related functions
* Hex, Oct-binary, octal, hexadecimal number converted to decimal function
* grep, Map-list advanced action function
A detailed description of these functions can be accomplished by using the command:
#perldoc-F functionname
Found
Common libraries
* File::basename-Get file name or file path based on path
* File::spec-through the combination of file name and path to fulfill the road
* File::find-recursively traverse all files in a directory
* Xml::simple-Represents an XML file in a complex structure and is quite handy to use
* Time::hires-often used to calculate the time spent on an operation
* Getopt::long-used when the script requires complex input parameters and options
* CWD-Get the current working directory
* Io::file-File operation
* Win32-I'll use it when I need to invoke some Windows APIs