Perl learning notes

xiaoxiao2021-03-06  24

[Last modified: February 5, 2005] 1 Notify The Administrator Regarding The Fa Disk Space Usage

#! / usr / bin / perl

# Purpose: This File Will Notify The Administrator Regarding The Disk Space usage.

Open (INF, "DF -K / USR / TEST / G / |");

While ($ line = )

{

IF ($ LINE = ~ m /. * / s (/ d ) /% /)

{

# x is The disk space hatold- percentage of disk space usage

$ x = $ 1;

IF ($ x> 55)

{

Open mail, "| mail qqq/@email.tom.com";

Print Mail "Reached to $ X% of Space Usage, please raise a s as soon as possible."

Close Mail;

}

}

}

2 Execute Command

$ OS_TYPE = 'uname -r';

3 string

In Perl, the end of the string does not contain an implicit NULL character, and NULL characters can appear anywhere in the string.

The antilactor can cancel the variable replacement

There are two differences between single quotes and dual quotation characters, one is there is no variable replacement function, and the other is that the anti-horns does not support escape characters, but only works when including single quotes and antilactors. Another feature of single quotes can be across multiple lines

Strings and values ​​translation: If the string contains non-digital characters, from the left to the first non-digital character.

4 floating point

The scope of the index is usually -309 to 308.

5 Default Value

In Perl, all simple variables have default initial values: "", ie empty characters.

6 Operators

** (Mattery): The base of the power cannot be negative

Integer comparison operator: <=> comparison, return 1, 0, or -1

0 - two values, etc. - the first value large-1 - the second value

String comparison operator LT is less than GT greater than EQ equal to Le less equal to GE greater than or equal to NE

CMP comparison, return 1, 0, OR-1

Do not use the bit to & to be used for negative integers, because Perl will convert them to unsigned numbers.

= As a sub-expression ($ A = $ b) = 3; equivalent $ a = $ b; $ A = 3;

In Perl can be used for strings, but when the tail character is 'Z', 'Z', '9'

$ stringvar = "agzzz"; $ Stringvar ; # $ stringvar now contacts "ahaaa"

$ Stringvar = "BC999"; $ Stringvar ; # $ stringvar now contacts "bd000"

-, Perl will first convert the string into a number and then reduce $ stringvar = "abc"; $ stringvar ---; # $ stringvar = -1 Now

Character string:. String Repeat: x

$ FRED = "Fred"; Print ("Hello,". $ fred. "! n") x 2); its result is: Hello, Fred! Hello, Fred! Common operator: The previous expression Operation, such as: $ VAR1 = 1, $ var2 = $ var1; equivalent to $ var1 = 1; $ var2 = $ var1; the only reason to use this operator is to improve the readability of the program, close Both two expressions, such as $ val = 26; $ results = ( $ VAL, $ VAL 5); # $ result = 32 Note If there is no parenthery, there is different: $ VAL = 26; $ result = $ VAL, $ VAL 5; # $ results = 27

7 From the standard input (stdin) to the variable value $ VAR = ; @Array = ; # ^ D is the symbol of the end input

8 list range (1..10) = (1, 2, 3, 4) (2, 5..7, 11) = (2, 5, 6, 7) 11) (3..3) = (3) Used in real (2.1..5.3) = (2.5..1.6) = () for strings ("AAA". "AAD") = ("AAA", "AAB", "AAC", "AAD") @Day_of_month = ("01". "31") can include variables or expressions ($ VAR1.. $ VAR2 5)

9 array output (1) @Array = (1, 2, 3); Print (@Array, "N"); result is: 123 (2) @Array = (1, 2, 3); Print ("@ Arrayn "); result is: 1 2 3

10 List / array length When the array variable appears where the expected simple variable appears, the Perl interpreter takes its length. @Array = (1, 2, 3); $ scalar = @Array; # $ scalar = 3, 即 @Array's length ($ scal) = @Array; # $ scal = 1, 即 @Array's first element Value Note: The number of times in array can be programmed: $ count = 1; while ($ count <= @Array) {print ("Element $ count: $ array [$ count-1] n"); $ count }

11 child number @Array = (1, 2, 3, 4, 5); @subarray = @Array [0,1]; # @subarray = (1, 2) @ Subarray2 = @Array [1..3]; # @ SUBARRAY2 = (2, 3, 4) @Array [0,1] = ("String", 46); # @Array = ("String", 46, 3, 4, 5) Now @Array [0. .3] = (11, 22, 33, 44); # @Array = (11, 22, 33, 44, 5) Now @Array [1, 2, 3] = @Array [3, 2, 4]; # @Array = (11, 44, 33, 5, 5) Now @Array [0..2] = @Array [3, 4]; # @Array = (5, 5, "", 5, 5) Now You can use sub-array form to exchange elements: @Array [1, 2] = @Array [2, 1]; 12 Related to the library function (1) sort - order @Array = ("THIS" in character order = ("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 number @ array2 = reverse (@Array); @Array2 = Reverse Sort (@Array ); (3) The meaning of the CHOP - array to tail CHOP is to remove the Stdin input string last character - newline character. And if it acts on an array, each element in the array is processed so. @List = ("Rabbit", "12345", "quartz"); Chop (@List); # @list = ("Rabbi", "1234", "quart") Now (4) join / split - connection / Split Join's first parameter is the intermediate character used to connect, and the remaining character arrays are to be connected. $ String = Join ("", "this", "is", "a", "string"); # 结果 为 为 "@list = (" words "," and "); $ String = Join ("::", @List, "colons"); # 结果 为 = w = =;; (:) "and", "colons") now

13 For the list (array) cycle of each element: Foreach

The syntax is: Foreach Localvar (Listexpr) {Statement_block;}: Foreach $ Word (@Words) {IF ($ Word EQ "The") {print ("Found The Word 'the'n");}} Note: ( 1) The cyclic variable LocalVar here is a local variable. If it already value before this, the value is still recovered after cycling. (2) Change local variables in the cycle, the corresponding array variables will also change, such as @List = (1, 2, 3, 4, 5); Foreach $ TEMP (@List) {IF ($ TEMP == 2 ) {$ TEMP = 20;}} At this point @List has become (1, 20, 3, 4, 5). 14 loop control Exit loop is LAST, the same as the Break in C; execute the next loop as next, the same effect as the CONTINUE in C; Perl unique command is REDO, its meaning is repeated this cycle, ie cycle variable The constant, returning to the cycle start point, but note that the redo command does not work in the DO loop.

15 Unicard condition syntax for Statement Keyword Condexpr. KEYWORD can be IF, unless, while or unsil, such as: Print ("this is zero.n") IF ($ VAR == 0); Print ("this is zero.n") unless ($ var! = 0 ); Print ("not zero yet.n") While ($ VAR -> 0); Print ("Not Zero Yet.n") Until ($ VAR - == 0); Although the condition is written behind, But it is performed first.

16 subroutine call call calls are as follows: 1, use & call & subname; ... Sub Subname {...} 2, first defined, you can omit the & symbol Sub Subname {...} ... subname; 3, Forward reference, first define sub-program name, then define sub-program Sub Subname; ... subname; ... Sub Subname {...} 4, use DO MY_SUB (1, 2, 3); etc. Validate & my_sub (1, 2, 3);

17 Subprogram Return Value default, the value of the last statement in the subroutine will be used as the return value. Statement Return (RetVal); you can also introduce a subroutine and return value RetVal, RetVal can be a list.

18 local variable

There are two ways to define local variables in subroutines: MY and LOCAL. The difference is that the variable defined by my definition exists in the subroutine; and the variable defined by the local does not exist in the main program, but exists in the subroutine that is called by the subroutine (no MY in Perl4). . You can assign it when defined, such as: My ($ scalar) = 43; Local (@Array) = (1, 2, 3);

19 subroutine parameters pass

1, Form & Sub1 (& Number1, $ Number2, $ Nubmer3); ... Sub Sub1 {MY ($ Number1, $ Number2, $ Number3) = @__; ...} 2, send array & addlist (@mylist); & addlist ("14", "6", "11"); & addList ($ value1, @SUBLIST, $ value2); ... sub addlist {my (@List) = @_; ...} The parameter is an array, The subroutine only assigns it to an array variable. Such as sub twolists {my (@ list1, @ list2) = @_;} @ List2 must be empty. However, simple variables and array variables can be passed at the same time: & twoargs (47, @mylist); # 47 Give $ SCALAR, @ MYLIST assignment to @List & twoargs; # @mylist's first element assigned to $ SCALAR, The rest of the elements are assigned to @List ... sub twoargs {my ($ scal, @List) = @__; ...} 20 to pass array parameters 1 with an alias, use the calling method to call & my_sub (@Array) Copy the data of array @Array to variables @_ in subroutines, when arrays, will cost more resources and time, and use alias Passings will not do these work, and direct operation of the array. Forms such as @MYARRAY = (1, 2, 3, 4, 5); & my_sub (* myarray); Sub my_sub {my (* Subarray) = @_;} 2, this method is similar to the transmission array in C language The start address pointer, but not the same, after defining the alias of the array, if there is a simple variable of the same name, the variable is also active. Such as: $ foo = 26; @foo = ("here", "a", "list"); & testsub (* foo); ... Sub testsub {local (* PrintArray) @_; ... $ printArray = 61;} When the subscriber is executed, the value of $ foo in the main program has become 61, and no longer 26. 3, use aliahe method to pass multiple arrays, such as @ array1 = (1, 3); @ array2 = (4, 5, 6); & two_array_sub (* array1, * array2); sub two_Array_sub {my ( * SUBARRAY1, * SUBARRAY2 = @_;} In this subroutine, SUBARRAY1 is an alias of Array1, and SUBARRAY2 is an alias of Array2. 21 predefined subroutine

Perl5 predefined three subroutines, performed at a specific time, they are called when the program is started; the End subrout is called at the end of the program; the AutoLoad subroutine is not found when a subroutine is not found transfer. You can define them yourself to perform what you need at a specific time. Such as: begin {print ("Hi! Welcome To Perl! N");} AutoLoad {Print ("Subroutine $ AutoS NOT FOUNDN"); # Variable $ AutoLoad Upset Subsessment Print ("arguments passed: @_n ");. 22 Note: // BDEF / Match $ DEFGHI, because $ is not as seen as a word.

23 Check All the failure Possibilities by inspecting $? Like this:

IF ($? == -1) {

Print "Failed to Execute: $! / N";

}

Elsif ($? & 127) {

Printf "Child Died with signal% D,% S Coredump / N",

($? & 127), ($? & 128)? 'With': 'without';

}

Else {

Printf "child exited with value% d / n", $? >> 8;

}

24 The Value of $! Is Meaningful Only Immediately After A Failure:

IF (Open (fH, $ filename) {

# Here $! Is meaningless.

...

} else {

# Only Here is $! Meaningful.

...

# Already here $! Might be meaningless.

}

# Since Here We Might Have Either Success OR Failure,

# here $! is meaningless.

25

SUB EXEC {

Local ($ OK, @cmd) = @_;

Foreach $ Word (@cmd) {

$ Word = ~ S # {} # $ name # g;

}

IF ($ OK) {

Local ($ OLD) = SELECT (stdout);

$ | = 1;

Print "@cmd";

SELECT ($ OLD);

Return 0 unsS = ~ / ^ y /;

}

CHDIR $ CWD; # Sigh

System @cmd;

CHDIR $ DIR;

Return! $?

}

26 LSTAT / STAT

If Stat Is Passed The Special FileHandle Consisting of An Underline, No Stat Is Done, But The Current Contents of The Stat Structure from The Last Stat, Lstat, OR FileTest Are Returned. Example:

IF (-x $ file && (($ d) = stat elsen, && $ d <0) {

Print "$ File IS Executable NFS File / N";

(This Works on Machines Only for Which The Device Number is Negative Under NFS.)

BECAUSE The Mode Contains Both The File Type and ITS Permissions, You Should Mask Off The File Type Portion and (s) Printf Using A "% O" if You Want to See the Real Permissions.

$ mode = (STAT ($ filename)) [2];

Printf "Permissions Are% 04O / N", $ MODE & 07777;

27 open the pipeline

The form of the program can also open and use the pipe (EX: LS> Tempfile) like the command line. Such as statement open (mypipe, "| cat> hello); open a pipe and send it to the MYPIPE output to become the input of" cat> hello ". Since the CAT command will display the content of the input file, the statement is equivalent to the Open (MyPipe, "> Hello"); sending the email with the pipeline as follows:

Open (Message, "| mail Dave");

Print Message ("Hi, Dave! Your Perl Program Sent this! / n");

Close (Message);

28 <> operator

<> The operator is actually an implicit reference to the array @argv, and its working principle is: 1. When the Perl interpreter first sees <>, open the file named in $ argv [0]; 2. Execute the action shift; that is, the element of the array @argv moves forward, and the number of elements is reduced. 3, <> operator reads all rows in the file opened in the first step. 4. After reading, the interpreter returns to the first step. Example: @argv = ("myfile1", "myfile2"); # actually assigns while by command line parameters ($ line = <>) {print ($ line);} will print the contents of the file myfile1 and myfile2.

29 Singleton Patten in Perl

package PSingleton; my $ oneTrueSelf; sub new {if ($ oneTrueSelf) {return $ oneTrueSelf;} else {my $ type = shift; my $ this = {presidents => [ 'George Washington', 'Thomas Jefferson', 'Theodore Roosevelt ',' Abraham Lincoln ']}; $ OneTrueSelf = Bless $ THIS, $ TYPE;}}

Reference:

Web Page Program - PERL Instance Analysis Tutorial

Perl Reference:

Documentation

Resource Topics

ProgrammingCore Documentation

转载请注明原文地址:https://www.9cbs.com/read-60438.html

New Post(0)