Bash detailed [transfer]

xiaoxiao2021-03-06  44

The easiest example - Hello World! Almost all explanations of programming books are the first example of the reader is a Hello World program, then we will start from this example today to gradually understand BASH. Edit a Hello file with a VI editor as follows: #! / Bin / bash # this is a us Simple Exampleecho Hello World This easiest Bash program is over. Here is a few questions, you need to explain: First, the first line #! What is the meaning of the first line, the first line of / bin / bash means three, the second line is a comment? Four, echo statement 5 The program #! Is the type of Hello file, which is a bit similar to the Windows system with different file suffixes to represent the meaning of different file types (but different). The Linux system determines the type of file based on the information behind "#!" and the string, and the classmates can be learned from the "man magic" command and / usr / share / magic file later. content. "#!" And "/ bash" in the first line in Bash, "/ bash" indicating that the file is a Bash program that needs to be explained by the Bash program under the / bin directory. Bash This program is generally stored in the / bin directory, if your Linux system is particularly special, Bash may also be stored in / sbin, / usr / local / bin, / usr / bin, / usr / sbin or / usr / local In this directory such / sbin; if you can't find it, you can use the "Locate Bash" "Find / -Name Bash 2> / dev / null" or "Whereis Bash" to identify the location of Bash; if Still can't find it, then you may need to install a BASH package yourself. The second line of "# this is a ..." is the annotation of the Bash program, from the "#" number in the Bash program (note: "outside the back is"! "To start to the end of the end It is seen as a comment for the program. The function of the three rows of ECHO statements is to output the strings behind the ECHO to the standard output. Since the Echo follows the "Hello World" string, "Hello World" is displayed on the screen of the console terminal. It should be noted that there is no semicolon at the end of the most statements in Bash. How to execute the program? There are two ways: one is explicitly developed Bash to perform: $ bash hello or $ sh hello (here SH is a link to Bash, "Lrwxrwrwx 1 root root 4 aug 20 05:41 / bin / sh -> Bash ") Or you can change the Hello file to the file that can be executed, then run it directly, at this time, due to the" #! / Bash "role of the first line of the Hello file, the system will automatically use the / bin / bash program to go Explain: $ chmod u x hello $ ./HELLO This is not directly "$ hello" because the current directory is not the default directory of the current user executable file, and the current directory "." Is set to the default directory is An unsafe setting. It should be noted that after the Bash program is executed, the Linux system is another process to run.

Variables and operations Let us first grasp the usage of variables in Bash, and then analyze the different variables in Bash and C language. The variables in Bash cannot contain a reserved word, and cannot contain "-" and other reserved characters, and the space cannot be included. Simple variables are unwanted in Bash, and there is no definition process such as "INT I". If you want to use a variable, as long as he is defined in front, it can be used directly. Of course, the first statement you use this variable should be assigned to him. If you don't assign the initial value, it doesn't matter. This variable is empty (note: NULL, not 0). Do not assign the initial value to the variable, although the syntax is not opposed, it is not a good program habit. Well, let's take a look at the following example: You first use the VI to edit the following file hello2: #! / Bin / bash # give the initialize value to strstr = "Hello World" Echo $ STR In this program we need to pay attention to the following : 1. When the variable is assigned, there is no space on both sides of '='. Second, the statement in Bash does not require semicolons (";"); third, in addition to assigning values ​​in the variable and in the For loop phoette, BASH Variable use must add "$" symbol before the variable, students can change the third line in the above program to "Echo Str" and try again, see what the result will be. 4. Because the Bash program is running in a new process, the variable definition and assignment in the program will not change the value of other processes or the same name variable in the original shell, nor does it affect their operation. More detailed documents are even referred to, but the variables enclosed in quotation will not be interpreted as variables, such as '$ str', which is seen as a pure string. Moreover, more standard variables are $ {str}, $ STR is alone, but a simplification of $ {str}. In complex circumstances (ie, it is possible to generate ambiguity) to use {} representation. Since the variable in Bash does not need to be defined, there is no type, one variable can be defined as a string, or it can be defined as an integer. If the variable is integrated, he is interpreted as an integer; if he is a string operation, he is seen as a string. Please see the example below: #! / Bin / bashx = 1999LET "x = $ x 1" Echo $ xx = "lympic '" $ Xecho $ X About integer variable calculations, there are few: " - * /% "They do the same meaning and literally.

Integer operations are generally implemented through two instructions of Let and Expr, such as the variable x plus 1 can be written: Let "x = $ x 1" or x = `expr $ x 1` In comparison operation, integer variables and The string variable is different. See the following table: The corresponding operation integer operation string operation is the same - Eq = Different -ne! = Greater than -gt> less than -LT

1. The variables in Bash need to add "$" symbols before the variable (the first assignment and the header of the FOR cycle); 2, there is no floating point operation in BASH, so There is also a variable that does not have a floating point type; 3, the comparison symbol of the plastic variable in Bash is completely different from the C language, and the arithmetic operation of the plastic variable also needs to handle it through the Let or EXPR statement; [Contents] - -------------------------------------------------- -------------------------- Enter the output About input, output, and error output in the character terminal environment, the concept of standard input / standard output is very good understanding. Enter the input to an application or command, whether it is from the keyboard input or from another file input; output is some information generated by the application or command; there is one in the Windows system, there is one under the Linux system. The concept of standard error output is mainly set for program debugging and system maintenance purposes. The error output can make some advanced error messages that make some advanced error messages do not interfere with normal output information, so that the usual user is used. In the Linux system: Standard input (stdin) defaults to keyboard input; standard output (stdout) defaults to screen output; Standard Error Output (stderr) is also output to the screen (STD in STDR). When using these concepts in Bash, the standard output is generally represented as 1, and the standard error output is represented as 2. Let us explain how to use them, especially standard outputs and standard errors. Input, output, and standard error output are mainly used for I / O redirections, that is to change their default settings. First, this example: $ ls> ls_result $ ls -l >> LS_RESULT The above two commands Redirect the results output of the LS command to the LS_RESULT file and append to the LS_RESULT file, not the output to the screen. ">" Is the representative symbol of the output (standard output and standard error output), two consecutive ">" symbols, ">>" means that the original and appended output is not cleared. Let's take a slightly complicated example: $ find / home -name lost * 2> err_Result This command has more "2" before "2", "2>" in the ">" symbol indicates redirection of the standard error output. Some directorys under the / home directory cannot be accessed due to permissions restrictions, thereby generating some standard error outputs in the Err_Result file. What results do you want to make a Find / Home -Name Lost * 2 >> ERR_RESULT command? If you do Find / Home -Name Lost *> All_Result, the result is that only the standard output is stored in the all_result file, what should I do if I want the standard error output and standard input? Look at the following example: $ find / home -name lost *> All_Result 2> & 1 Top This example will first redirect the standard error output to the standard output, and then redirect the standard output to all_result this file. This way we can store all the output to the file.

In order to achieve the above functions, there is an easy way to write as follows: $ find / home -name lost *> & all_Result If the error information is not important, the following command can allow you to avoid the unique error information: $ FIND / Home -Name Lost * 2> / dev / null students can also try again to try the following to the following redirect methods, see what the results will be, why? $ FIND / Home -Name Lost *> All_Result 1> & 2 $ FIND / HOME -NAME LOST * 2> All_Result 1> & 2 $ FIND / HOME -NAME LOST * 2> & 1> All_Result another very useful redirection The operator is "-", please see the following example: $ (CD / Source / Directory && Tar CF -) | (CD / DEST / DIRECTORY & TAR XVFP -) This command represents all the / source / directory directory Files are compressed and unzipped, quickly moving to the / DEST / DIRECTORY directory, this command will display special advantages when / source / directory and / dest / directory are not in the same file system. There are still few uncommon usage: n <& - indicates that the N number is turned off <& - indicates the closing standard input (keyboard) n> & - indicates that the N number is turned off> & - means the standard output is turned off [directory] -------------------------------------------------- ------------------------------ The basic process control syntax in the process Control Syntax Bash contains all controls commonly used in C language Structure, such as conditions branches, cycles, etc., will be introduced one by one. If ... Then ... Elseif statement is used to judge and branch, and its grammar rules and the IF of the C language is very similar. Several basic structure which is: if [expression] then statmentsfi or if [expression] then statmentselse statmentsfi or if [expression] then statmentselse if [expression] then statments else statmentsfi or if [expression] then statmentselif [expression] then statments else statmentsfi It is worth explanating if you write if and then simple writing in a row, you must add a semicolon in front of THEN, such as: if [expression]; THEN, the following example shows how to use the IF condition judgment statement: #! / BIN / BASHIF [$ 1 -gt 90] Then Echo "Good, $ 1" Elif [$ 1 -gt 70] Then Echo "OK, $ 1" Else Echo "Bad, $ 1" FIEXIT 0 above the above example is the first of the command line A parameter, this will explain in the "special reserved word in Bash in Bash".

The FORFOR loop structure is different in the C language, and the basic structure of the for loop in Bash is: for $ var in [list] do statentsdone, $ var is a loop control variable, [list] is a collection of traversal to Var, DO / DONE pairs contain a circulation, equivalent to a pair of braces in the C language. In addition, if DO and FOR are written in the same line, it must be added to the front of DO .;;;;;; Such as: for $ VAR IN [list]; do. Here is an example of using for loop: #! / Bashfor day in sun mon Tue Wed Thu Fri Satdo Echo $ Daydone # If the list is included in a pair of dual quotes, it is considered to be an element for day in. Sun Mon Tue Wed Thu Fri Sat "Do Echo $ DaydoneExit 0 Note The above example, the variable DAY in the line where the line is not added to the" $ "symbol, and in the cyclic body, the ECHO variable amount $ DAY is necessary to add The "$" symbol is on. In addition, if you are written into the in [list] section, DAY will take all the parameters of the command line. Such a program: #! / Bin / Bashfor Paramdo Echo $ ParamdoneExit 0 The above program will list all command line parameters. The circulator of the FOR cycle structure is included in the Do / Done pair, which is also the characteristics of the following While, the Until cycle. The basic structure of the WhileWhile loop is: while [condition] do statentsdone, please write an example to verify it yourself. The basic structure of the UnTiluntil cycle is: until [condition is true] do statentsdone This structure also please write an example to verify it. The CASEBSH in the CASEBSH is similar to the functionality of the Switch statement in the C language, which can be used to perform multiple branch controls. Its basic structure is: case "$ var" in condition1) statments1 ;; condition2) statments2 ;; ... *) Default stat States ;; ESAC below this program is an example of branching using the CASE structure: #! / Bin / bashecho "Hit a Key, Then Hit Return" $ keypress "in [az]) Echo" limited letter ";; [AZ]) Echo" Uppercase Letter ";; [0-9]) ECHO" DIGIT "; ; *) Echo "Punctuation, Whitespace, or other" ;; ESACEXIT 0 The READ statement in the "Read KeyPress" in the above example represents the read input from the keyboard. This command will explain in other advanced issues of the BASH of this. Break / Continue is familiar with C language programming is familiar with BREAK statements and Continue statements. There are also these two statements in Bash, and the roles and usage are the same as the C language. The BREAK statement allows the program process to completely jump out of the current cycle body, and the Continue statement can skip the remainder of the cycle and directly enter One cycle.

[table of Contents]----------------------------------------------- ------------------------------- Function function The use of Bash is a relatively simple scripting language, but for the convenience structure Design, the function defined in Bash is also provided. The function definition in Bash is very simple, as long as you write below: function my_funcname {code block} or my_funcname () {code block} The second write method is closer to the WI in the C language. The definition of the required function in Bash must be used before the function is used, and the C language is different from the header file description function method. A further problem is how to deliver parameters and get the return value. The definition of the function parameters in Bash does not need to be set at the function definition, but only need to use Bash's reserved variable $ 1 $ 2 when the function is called; the return value of Bash can be specified with the RETURN statement Returns a specific integer. If there is no return value explicitly returns a return value, the return value is the result of the last statement of the function (generally 0, if the execution failed returns an error code). The return value of the function is obtained in the program body that calls the function. Let's take a look at an example of using a function to calculate the topic: #! / Bin / bashsquare () {let "Res = $ 1 * $ 1" Return $ RES} Square $ 1RESULT = $? Echo $ ResulTexit 0 [directory] -------------------------------------------------- ---------------------------- Bash Shortcuts About BASH Shortcock Ctrl U under the Console Ctrl U Delete All characters before the cursor Ctrl D Deletes a character Ctrl K before the cursor to remove all character Ctrl h after cursor, and remove a character Ctrl t after the cursor will change the cursor, the first two characters of the cursor Ctrl A move the cursor to the front Ctrl e move The cursor to the last side Ctrl P Previous command ctrl n Next command CTRL S lock input Ctrl Q release Ctrl f Move the cursor to the latter Ctrl b Move the cursor to the previous character CTRL X Mark a location Ctrl C Clear the current input [directory] ------------------------------------------------------------------------------------------------------ -------------------------------------- Gawkawk is a programming language, for documentation Treatment has a strong function. The AWK name is named by the first letter of the three initial designers: Alfredv.aho, Peterj.Weinberger, Brianw.kernighan. AWK was originally completed in 1977. In 1985, a new version of AWK was published, and its function enhanced a lot than the old version. AWK can modify, compare, extraction, printing, etc. in a short program. If you write a language code such as C or PASCAL, you will be very inconvenient and it takes time, and the program written will be large. AWK is not just a programming language, but it is an indispensable tool for Linux system administrators and programmers. The AWK language is very good, easy to master, and special flexibility. Gawk is the awk made from the GNU program, Gawk initially completed in 1986, and then constantly improved, updated. Gawk contains all the features of awk. There are basically two ways to perform a Gawk program.

If the Gawk program is short, you can write Gawk directly on the command line, as shown below: Gawk'Program'Nput-file1Input-file2 ... where Program includes some Pattern and Action. If the Gawk program is longer, the more convenient approach is to exist in a file, and the Gawk's format is as follows: gawk-file2 ... The file of the Gawk is more than one file, performing a Gawk format As shown below: gawk-fprogram-file1-fprogram-file2 ... input ... [directory] ----------------------- -------------------------------------------------- ------ Documents, Records, and Fields In general, Gawk can handle numerical data in the file, but you can also process string information. If the data is not stored in the file, you can provide input to Gawk via a pipe command and another redirect method. Of course, Gawk can only process text files (ASCII code files). The telephone number is a simple example of a file that Gawk can handle. Phone number This is composed of many items, and each entry has the same format: surname, name, address, phone number. Each entry is arranged in alphabetical order. In Gawk, each such entry is called a record. It is a collection of complete data. For example, this entry in the phone number book, including his address and phone number, is a record. Each of the records is called a field. In Gawk, the field is the most basic unit. A collection of multiple records consists of a file. In most cases, the fields are separated from a special character, like space, tab, semicolon, etc. These characters are called field separators. Please see this / etc / passwd file: tparker; T36S62HSH; 501; 101; TIMPARKER; / home / tparker; / bin / BashetReijs; 2ys639dJ3H; 502; 101; EDTREIJS; / HOME / ETREIJS; / BIN / TCSHYCHOW; 1H27SJ; 503; 101; Yvonnechow; / home / ychow; / bin / bash you can see the / etc / passwd file uses a semicolon as a field separator. Each row in the / etc / passwd file includes seven fields: user name; password; user ID; Working Group ID; Note; Home Directory; started housing. If you want to find the sixth field, you only need to have a number of five sections. But considering the following phone number book, you will find some questions: smithjohn13wilsonst.555-1283smithjohn2736artsidedrapt12355-2736smithjohn1255-2736smithjohn125westmountMountCr555-1726 Although we can tell each record including four fields, Gawk is not powerful. Phone number This is used as a separator, so Gawk thinks Smith is the first field, and John is the second field, 13 is the third field, and push it according to the next class. In terms of Gawk, if you use spaces as a field separator, the first record has six fields, while the second record has eight fields. So, we must find a better field separator.

For example, using slash as a field separator: smith / john / 13wilsonst. / 555-1283smith / john / 2736artsidedr / APT / 123 / 555-2736SMITH / 125WESTMOUNTCR / 555-1726 If you don't specify other characters As a field separator, Gawk uses spaces or Tabs as a field separator by default. [table of Contents]----------------------------------------------- -------------------------------- Mode and action Each command in the Gawk language consists of two parts: one Pattern and a corresponding action (Action). As long as the mode is in line with, Gawk will perform the corresponding action. The mode part is enclosed in two slant bars, and the action part is enclosed in a pair of rough brackets. For example: / pattern1 / {anctions1} / pattern2 / {action2} / pattern3 / {anctions All GAWK programs are composed of such a pair of pairs of patterns and actions. The mode or action can be omitted, but two cannot be omitted simultaneously. If the mode is omitted, the action will be performed for each row in the input file. If the action is omitted, the default action is executed, which exhibits all the input rows that match the pattern without any changes. Here is a simple example because the Gawk program is short, so write the Gawk program directly on the casing command line: gawk '/ tparker /' / etc / passwd This program is looking for the / etc / passwd file in the above-mentioned TPARKER The record is recorded and displayed (there is no action in this example, so the default action is performed). Let's look at an example: Gawk '/ UNIX / {Print $ 2}' file2.data This command looks an enlarged file containing the file2.data file containing UNIX and prints the second field of these records. You can also use multiple modes and action pairs in a command, for example: gawk '/ scandal / {print $ 1} / rumor / {print $ 2}' gossip_file This command search file gossip_file includes Scandal record, and prints the first Field. Then, search the gossip_file from the head, including the record of Rumor, and print the two fields. [table of Contents]----------------------------------------------- --------------------------------- Computing Gawk has a lot of comparative operators, the following lists are listed: = = Equal! = Not equal> greater than = greater than or equal to <= less than or equal to, for example: Gawk '$ 4> 100'TestFile will display those records in the file TestFile greater than 100 records. The following table lists the basic numerical operators in Gawk. Operator Description Example Addition operation 2 6- subtraction operation 6-3 * Multiplication 2 * 5 / division operation 8/4 ^ Multiping calculation 3 ^ 2 (= 9)% Survival 9% 4 (= 1) For example : {Print $ 3/2} Displays the result of the third field by 2. In Gawk, the priority of the operator and the priority of the general mathematical operation. For example: {Print $ 1 $ 2 * $ 3} Displays the second field and the third field, then add the result of the first field. You can also change priority in parentheses. For example: {Print ($ 1 $ 2) * $ 3} Displays the first field and the second field, then multiplied with the third field.

[table of Contents]----------------------------------------------- -------------------------------- Internal function Gawk has various internal functions, now in the following: SQRT X) Scepter-square root SIN (X) seeking X for x Sinusic Function COS (X) Seeking X of the cosine function ATAN2 (X, Y) Seeking X / Y's remainder Download Log (X) Seeking Natural logarithmic Exp ( X) Asking X of the E-Part INT (X) to find the integer part of the integer part of the X (), the random number SRAND (X) between 0 and 1 sets X to rand () of the number of seeds in DEX (in, find) Looking for a string Find to appear in the string in in the string in, the return value is the location of the string Find appears in the string in. If the string Find cannot be found in the string in, the return value is 0. For example: PrintEx ("peanut", "an") display result 3. Length (String) finds a string a few characters. For example: Length ("abcde") display result 5. Match (string, regexp) looks for the longest and leftmost sub-string in accordance with the REGEXP in the string String. The return value is regexp at the beginning of String, ie index value. The MATCH function will set the system variable RSTART equal to the value of INDEX, and the system variable RLength is equal to the number of characters that meet. If it does not match, RSTART is set to 0, and RLEngth is -1. Sprintf (Format, Expression1, ...) and Printf are similar, but Sprintf does not display, but returns a string. For example: Sprintf ("PI =%. 2f (approx.)", 22/7) The string returned to PI = 3.14 (Approx.) SUB (Regexp, Replacement, Target) Find the most in accordance with REGEXP in string Target Long, the leftmost place, replaced the leftmost regexp with string replacement. For example: str = "Water, Water, Everywhere" SUB (/ at /, "ITH", STR) Result String STR will become Wither, Water, Everywheregsub (Regexp, Replacement, Target) is similar to the previous SUB. Find all parts that match Regexp in a string Target, replacing all replanpps with string Replacement. For example: str = "Water, Water, Everywhere" GSUB (/ at /, "ITH", STR) Result String STR will become Wither, Wither, EverywhereSubstr (String, Start, Length) Returns String String Strings The length of this sub-string is Length, starting from the position of the START. For example: Substr ("Washington", 5, 3) The return value is ing if there is no Length, the returned substring begins to the end of the position of the START. For example: Substr ("Washington", 5) return value INGTON. TOLOWER (String) Change the uppercase letters of the string String to lowercase letters.

For example: TOLOWER ("MixedCase123") return value is MixedCase123. TouPper (String) Changes the lowercase letters of the string String to uppercase letters. For example: TouPper ("MixedCase123") return value is MixedCase123. The internal function close (filename) of the input and output closes the input or output file filename. System (Command) This function allows the user to perform an operating system instruction, will return to the Gawk program after execution. For example: begin {system ("ls")} [directory] -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -------------------------------------------- string and numeric strings It is a series of characters that can be translated by Gawk. The string is enclosed in double quotes. The numbers cannot be enclosed in double quotes, and Gawk will be used as a value. For example: Gawk '$ 1! = "TIM" {print}' testfile This command will display all records of the first field and Tim. If the tim in the command does not need double quotes, Gawk will not be executed correctly. Another example is: Gawk '$ 1 == "50" {print}' testfile This command will display all the first fields and 50 strings of the same record. Gawk is only a typically compared regardless of the size of the value in the first field. At this time, the string 50 and the value 50 are not equal. We can let the action show some complicated results. For example: Gawk '$ 1! = "TIM" {Print $ 1, $ 5, $ 6, $ 2}' testfile You can also use some change in the modified control formatted the output. The reason why Gawk has a special explanation for these symbols. The commonly used modifier controls are listed below: a warning or ringing characters. Backward. f converted. Wrap. Enter. Tab. V Vertical Tab. In Gawk, the default field separator is typically spaced or tab. But you can change the character separator using the -f option on the command line, just following the separator you want to use after -f. GAWK-F ";" '/ tparker / {print}' / etc / passwd In this case, you set the character separator as the ingredient. Note: -f must be capitalized and must be before the first quotation marks. [table of Contents]----------------------------------------------- ------------------------------- Yuan Character Gawk language has its own special rules in the format match. For example, CAT can match the fields of these three characters in any location in the record. But sometimes you need some more special match. If you want to match Cat only with the control, you need to add spaces on both ends: / cat / {print}, for example, you want to match both CAT and CAT, you can use or (|): / CAT | CAT / {print} In Gawk, there are several characters having special meaning. The following listings are listed below: • The beginning of the field. For example: $ 3 ~ / ^ b / If the third field begins with character b, it matches. ? $ Indicates the end of the field. For example: $ 3 ~ / b $ / If the third field ends with character b, it matches. Indicates to match any single character m. For example: $ 3 ~ / i.m / If the third field is character i, it matches. ? | Expression "or". For example: / Cat | CAT / and CAT or CAT characters match. ? * Indicates zero to repeat the character.

For example: / UNI * X / and UNX, UNIX, UNIIX, UNIIIX, etc. ? Indicate characters to repeat multiple times. For example: / UNI X / and UNIX, UNIIX, etc. match. ? {a, b} indicates the repetition between the character A to B times. For example: / UNI {1, 3} X and UNIX, UNIIX and UNIIIX match. ?? Indicates the character zero and once. For example: / UNI? X / and UNX and UNIX match. ? [] Indicates the range of characters. For example: / i [bdg] m / and IBM, IDM, and IGM matching? [^] Indicates the characters not in []. For example: / i [^ DE] m / and all of the three characters of the two characters, including the IDM and IEM, in addition to the IDM and IEM. [table of Contents]----------------------------------------------- ---------------------------------- Call the Gawk program When you need a lot of patterns and action, you can write a Gawk Program (also called a Gawk script). In the Gawk program, you can omit the quotation marks on both sides of the action, because in the Gawk program, the mode and the action start and it is obvious when it ends. You can call the Gawk program with the following command: gawk-fscriptfilename This command enables Gawk to perform a Gawk program named Script on the file filename. If you don't want to use the default field separator, you can specify a new field separator after the F option (of course you can also specify in the Gawk program), for example, using a semicolon as a field separator: Gawk -fscript-f ";" FileName If you want the Gawk program to handle multiple files, each file name is listed: Gawk-fscriptfilename1FileName2FileName3 ... By default, the output of Gawk will be sent to the screen. But you can use Linux's redirection command to make Gawk's output to a file: Gawk-fscriptFileName> Save_file [directory] ---------------------------------------------------------------------------------------------------------------- -------------------------------------------------- ----- Begin and End have two special patterns very useful in Gawk. Begin mode is used to indicate that Gawk starts to process some actions before processing a file. BeGin is often used to initialize values, set parameters, and the like. End mode is used to perform some instructions after the file processing is complete, generally used as a summary or comment. All instructions to be executed in BeGin and End should be enclosed in the parentheses. Begin and End must use uppercase. Please see the example below: Begin {print "StartingTheProcessthefile"} $ 1 == "Unix" {print} $ 2> 10 {Printf "thislinehasavalueof% D", $ 2} end {print "finishedProcessingThefile.bye!"} In this program, first Display a message: StartingTheProcessthefile, then display all the first fields to the entire record of UNIX, then display the record of the second field greater than 10, and finally display information: finished processingthefile.bye !.

[table of Contents]----------------------------------------------- ------------------------------- Variables in Gawk, you can assign a variable by the equal sign (=): Var1 = 10 In Gawk, you don't have to declare the variable type in advance. Please see the following example: $ 1 == "plastic" {count = count 1} If the first field is plastic, the value of count is added 1. Prior to this, we should give COUNT to the initial value, usually in the Begin section. The following is a relatively complete example: begin {count = 0} $ 5 == "Unix" {count = count 1} end {printf "% docurrencesofunixweFound", count} variables can be used with the fields and values, so the following expression The style is legal: count = count $ 5 VAR1 variable can also be part of the format, for example: $ 2> max_value {print "maxValueexceedededby", $ 2-max_value} $ 4-var1gawk language has several very Useful built-in variables are now listed below: NR has read the number of records. FNR reads the number of records read from the current file. FileName Enter the name of the file. FS field separator (default space). RS record separator (default is a wrap). Ofmt digital output format (default% g). OFS output field separator. ORS output record separator. NF number of fields in the current record. If you only process a file, the value of NR and FNR is the same. However, if it is multiple files, NR is for all files, while FNR is just for the current file. For example: NR <= 5 {Print "NOTENOUGHFIELDSINTHERECORD"} Check if the number of records is less than 5, if less than 5, the error message is displayed. FS is very useful because FS controls the field separator of the input file.

For example, in the Begin format, use the following command: fs = ":" [directory] -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -------------------------------------------------- The syntax of the control structure if expression IF expression is as follows: if (expression) {commands} else {commands}, for example: #asimpleifloop (IF ($ 1 == 0) {Print "this cell Has a value of zero"} else {printf "THE VALUE IS% D", $ 1}) Next example: #Nanely Form Attedi Floop ($ 1> $ 2) {print "The first column is larger"} else {print "The second column is larger"} ) syntax while loop while loop as follows: while (expression) {commands} example: #interest calculation computes compound interest # inputs from a file arethea mount, interest_rateandyears {var = 1while (var <= $ 3) {printf ( "% f" , $ 1 * (1 $ 2) ^ var) syntax var for loop for loop as follows: for (initialization; expression; increment) {command} example: #interest calculation computes compound interest # inputs from a fil earethea mount, interest_rateandyears {FOR (var = 1; var <= $ 3; var ) {printf ("% f", $ 1 * (1 $ 2) ^ var)}} NEXT and EXITNEXT instructions to tell the next record in the Gawk handling file, And no matter what is now doing. The syntax is as follows: {Command1Command2Command3nextCommand4} The program jumps to the next record from the header command as long as the NEXT directive is executed. Therefore, in this example, the Command4 instruction will never be executed. After the program encounters the exit command, go to the end of the program to execute the end, if there is an end. [table of Contents]----------------------------------------------- ------------------------------- Array GAWK language supports array structure. The array does not have to initialize in advance. Declare an array method as follows: ArrayName [NUM] = Value Please see the following example: #reverse line in a file {line [nr] = $ 0} #remember each linend {var = nr #output lines in reverse OrderWhile (Var> 0) {PrintLine [var] var -} This program reads each row of a file and is displayed in the opposite order. We use NR as the subscript of the array to store each record of the file, and then start from the last record, display the files one by one.

[table of Contents]----------------------------------------------- -------------------------------- Custom Function User Custom Function Complex Gawk program can often use your own defined Function is simplified. Call the user-defined function as the method of calling internal functions. The definition of the function can be placed anywhere in the Gawk program. The format of the user-defined function is as follows: functionName (parameter-list) {body-of-function} name is the name of the defined function. A correct function name can include a sequence of letters, numbers, and underscores, but not using numbers. Parameter-List is a list of all parameters of the function, and each parameter is separated by a functions. Body-of-function contains Gawk expressions, which is the most important part of the function definition, which determines what the function is actually doing. The following example is added to the square of the value of each record of the first field of each record, and the square of the value of the value of the second field. {Print "SUM =", Squaresum ($ 1, $ 2)} Function SquareSum (X, Y) {Sum = x * x y * Yreturnsum} [directory] --------------- -------------------------------------------------- ---------------- Several examples finally raised several Gawk examples: gawk '{if (nf> max) max = nf} end {printmax}' This program will display The maximum number of fields in all input lines. Gawk'Length> 80 'This program displays each row of more than 80 characters. There is only the mode to be listed here, and the action is displayed throughout the record. Gawk'nf> 0 'shows all rows that have at least one field. This is a simple way to delete all blank lines in a file. Gawk'begin {for (i = 1; i <= 7; i ) Printint (101 * rand ())} 'This program will display 7 random numbers between 0 and 100. LS-LFILES | GAWK '{x = $ 4}; end {print "Totalbytes:" x} "This program displays all the total number of bytes of all specified files. ExpandFile | Gawk '{IF (x end {print "X}' This program displays the length of the longest line in the specified file. EXPAND will change Tab to Space, so it is used to use the actual right border. Comparison .Gawk'begin {fs = ":} {Print $ 1 |" sort "} '/ etc / passwd This program will display all users' login names, in accordance with the order of letters. Gawk' {nLines } end { Printnlines} 'This program displays the total number of files. The number of files will be displayed in this program, but the total number of files will be displayed, but the work of calculating the number of lines is made by gawk. Gawk' {printnr , $ 0} 'This program displays the contents of the file, the line number is displayed at the top number of each line, and its function is similar to' CAT-N '.

[table of Contents]----------------------------------------------- --------------------------------- PerlperL's basic feature "Don't expect to experience all of Perl in an hour At the moment, this situation is very like eating bananas. After you don't have to eat a banana, you will know the taste. Every bit bite is enjoyed, and you will have a bit a bit, and then a bit. "The above words is Perl Project sponsor Lauley Wall (Larrywall) to learn a classic comment on Perl language, I hope everyone can find this feel. Perl's design goals are to help UNIX users complete some common tasks, these tasks are too heavy for shells or is too stringent for transplantation requirements. The syntax of several languages ​​of C, C , Shell, Script, Sed, AWK, in the Perl language, the original purpose is to replace the combination of SED / AWK and scripting languages ​​in UNIX, used to make information, generate Report. Therefore, the Perl language is far more complex and powerful than the previously described BASH. Perl design principles or PERL design philosophy is to be practical as first priority, that is, try to make Perl language easy to use, efficient, and complete. Perl is distributed in the form of two licenses in GnupublicLicense and ArtictClicense. It is an open source software, free software, originally running in UNIX and class UNIX systems, which can now be conveniently in OS / 2, Windows9x, Windows / NT and other systems. Run down. Perl is a language that explains the run. Like the Bash program, the first line of the general Perl program needs to be indicated by a Perl program instead of the shell program, so it generally will under the following row statements: #! / Usr / bin / perl The first line of the file. Perl is getting stronger and stronger than the version of the module is introduced into the module. Now Perl's functionality is beyond the imagination of original design, almost anything can be done, and it has become a standard tool for each workstation. The most famous thing in Perl is the processing of the string, because the Internet's huge demand for text information processing, making Perl's application in the day, and the Perl language is indeed a very excellent text information handling language. A useful Perl program can be short. For example, you want to change some of the same content in a large number of files, you can use the following command: Perl-e's / gopher / worldwideweb / gi'-pi.bak * .html The following is a basic Perl program: #! / Usr / local / Bin / Perl ## ProgramTodotheObviousPrint'HelloWorld. '; # just simply displaying the HelloWorld. string. [table of Contents]----------------------------------------------- ------------------------------- Variable Perl has three variables: scalar, array (list), and related arrays. The most basic variable type in Perl is scalar. The scalar can be both numbers or a string, and both can be interchangeable. Specifically, numbers or strings can be determined by context. The syntax of the scalar variable is $ VARIABLE_NAME. For example: $ priority = 9; give 9 Scale Variable $ Priority, you can also give the string to the variable: $ priority = 'high'; Note In Perl, the size of the variable name is sensitive, so $ A and $ A is different variables.

The following values ​​or strings can be assigned: 12312.45E-100xFF (HEX) 0377 (Octal) 'What You $ SEEIS (Almost) What YouGet'don'twalk' "Howareou?" "SubstituteValueSof $ Xand in" quotes. "` Date``uptime-u`u-sk $ filespec | sort-n `$ x $ list_of_things [5] $ {'} It can be seen from above, there are three types of references in Perl. Double quotes ("") Any scalar and special sense of the character string will be interpreted by Perl. If you do not want to explain any scales and special characters in the string, you should enclose the string with a single bracket. At this time, Perl does not explain any of these characters, except and '. In the end, it can be enclosed in (`), so that the command can run normally and get the return value of the command. Please see the example below. : 1 #! / Usr / bin / perl2 $ folks = "100"; 3Print "$ fundks = $ fundks"; 4Print '$ FOLKS = $ FOLKS'; 5PRINT "Beep! AlsomeBlankelineShere"; 6 $ date = `Date % D `; 7Print" Todayis [$ DATE] "; 8chop $ DATE; 9PRINT" DateAfter "DateAfterchoppingOffCarriagereturn: [". $ DATE. "]"; Note that the actual program should not include the line number. The output results are as follows: $ fundks = 100 $ fundks = $ FOLKSBEEP! Someblanklinesheretodayis [03/29/96] DateAfterChoppingOffCarriagerturn: [03/29/96] Line 3 displays the value of $ FOLKS. You must use a modifier before you can display the string $ fundks instead of $ funds. Value 100. The fourth line is used in single quotes, and the results of Perl do not explain any of them, but the string is not displayed. The six line is (`), then the Date % D command execution result Stored in Scale $ DATE. Used in the above example, some of the characters have a particular meaning: the meaning of these characters: Return. Enter. Table .a Beep. Backspace.le Between L and E The characters are converted into lowercase .L converted the following characters to lowercase. U and the characters between U and E transition to uppercase. U conversion into uppercase .cc insertion Control characters C. X ## 十 进 进数 ##. OOO OOO OOO. Anti-slope. Output the next character as it is, for example: $ output $. The numbers in Perl are stored in floating point. The following is listed below: $ A = 1 2; # 1 plus 2, the result is stored in $ A. $ A = 3-4; # 3 minus 4, the result is stored in $ A. $ A = 5 * 6; # 5 Take 6, the result is stored in $ A. $ A = 7/8; # 7 is stored in $ A by 8 and the results are stored. $ A = 9 ** 10; # 9 10 times, the result is stored in $ A. $ A = 5% 2; # 取 5 Except for 2, the result is stored in $ A. $ A; # $ A plus 1, then give $ A. $ A ; # #,, then add 1. $ a; # $ 1 minus 1, then give $ A.

$ A -; # first, then $ A is 1. Perl supported logical operators: $ r = $ x || $ y $ r = $ x or $ y. $ r = $ x && $ y $ r = x and $ y. $ R =! $ x $ r = Non-x. For character scales, Perl supports the following operators: $ a = $ b. $ C; # Connect $ B and $ C and give $ A. $ a = $ bx $ c; # $ b Repeat $ C, then give $ A. Below is the assignment method in Perl: $ a = $ b; # give $ B to $ A. $ A = $ b; # $ b plus $ A, then give $ A. $$ a - = $ b; # $ a minus $ b, then give $ A. $ a. = $ b; # Connect $ b to the back of $ A and give $ A. You can also use the following comparative operators: $ x == $ y Returns true if $ x and $ y are equal. $ x! = $ y Returns true if $ x and $ y are not equal. $ x <$ y is true if the $ x is smaller, then returns true. $ x <= $ y Returns true if the $ x is less than or equal to y. $ x> $ y If the $ x is large, return true. $ x> = $ y Returns true if $ x is equal to $ y. $ Xeq $ y returns true if the string is the same as the string $ y. An array array is also called a list, which consists of a series of scales. The array variable begins with @. Please see the following assignment statement: @food = ("apples", "pears", "eles"); @ music = ("whistle", "flute"); the subscript of the array begins, you can use square brackets Quote the subscript of the array: $ FOOD [2] Returns EELS. Note @ has become $, because EELS is a scalar. In Perl, there are a variety of assignment methods, such as @Moremusic = ("Organ", @ music, "harp"); @ moremusic = ("Organ", "WHISTLE", "Flute", "HARP"); There is also a way to add new elements to an array: Push (@food, "eggs"); add EGGS to the end of the array @food. To add multiple elements to the array, you can use the following statement: Push (@food, "eggs", "limited"); push (@food, "(" eggs "," limited ")); push (@food, @MOREFOOD; Push Returns the new length of the array. The POP is used to delete the last element of the array and returns the element.

For example: @food = ("apples", "pears", "elelex"); $ grub = pop (@food); # this time $ grub = "EELS" Please see the following example: 1 #! / Usr / bin / perl2 # 3 # AnexampletoshowaRaysworkinperl4 # 5 @ Amounts = (10, 24, 39); 6 @ parts = ('Computer', 'Rat', "KBD"); 78 $ a = 1; $ b = 2; $ C = '3'; 9 @ count = ($ A, $ B, $ C); 1011 @ Empty = (); 1213 @ spare = @ Parts; 1415Print '@ Amounts ='; 16Print "@amounts"; 1718print '@ Parts = '; 19Print "@parts"; 2021Print' @ count = '; 22Print "@count"; 2324Print' @ Empty = '; 25Print "@empty"; 2627Print' @ spare = '; 28Print "@spare"; 293031; # 32 # AccessingindIndividualItemsinanArray33 # 34Print '$ Amounts [0] ='; 35PRINT "$ AMOUNTS [0]"; 36Print '$ Amounts [1] ='; 37Print "$ AMOUNTS [1]"; 38Print '$ Amounts [2] = '; 39Print "$ AMUNTS [2]"; 40Print' $ Amounts [3] = '; 41PRINT "$ AMOUNTS [3]"; 4243Print "itemsin @ amounts = # Amounts; 44 $ size = @ Amounts; Print "Sizeofamount = $ size"; 45print "item0in @ Amounts = $ Amounts [$ []"; The following is the result: @ Amounts = 102439 @ parts = computerratkbd @ count = 123 @ Empty = @ spare = computerratkbd $ Amounts [0] = 10 $ AMOUNTS [1] = 24 $ Amounts [2] = 39 $ AMOUNTS [3] = itemsin @ Amounts = 2SizeOFAMount = 3Item 5 line, three integer values ​​gave array @amounts. Chain 6, three characters are served to array @parts. Chapter 8, strings and numbers assigned to three variables, and then assigning three variables to array @count. 11 line created an empty number. 13 The array @spare is assigned to the array @Parts. 15 to 28 rows Output the top 5 lines shown. 34 to 41 lines each of the elements of array @amounts separately.

Note $ AMOUNT [3] does not exist, so an empty item is displayed. 43 rows Use the $ # array mode to display the last subscript of an array, so the magnitude of the array @amounts is ($ # Amounts 1). The 44 line assigned a number to a scalar, then assigns the size of the array to the scalar. 45 rows use a special variable $ [to represent an array (default 0). Related arrays a general array allows us to access the elements of them by numbers. For example, the first element of the array @food is $ food [0], the second element is $ food [1], and so on. But Perl allows you to create a related array so that we can access arrays through a string. In fact, each subscript index in a related array corresponds to two entries, the first entry is called keyword, and the second entry is called a value. This way, you can read the value by keywords. The associated group name is based on a percent sign (%), reference entry by curly bracket ({}). For example:% AGES = ("Michaelcaine", 39, "Dirtyden", 34, "Angie", "Willy", "THEQUEENMOTHER", 108); so we can read arrays by the following method Value: $ organ {"michaelcaine"}; # returns39 $ with {"dirtyden"}; # returns34 $ with {"angie"}; # returns27 $ with {"willy"}; # returns "21indogyears" $ Ages {"ThequEenmother "}; # Returns108 [directory] -------------------------------------------------------------------------------------------------------------------------------------------------- -------------------------------------- File Operation File Handle and File Operation We can pass the following The program understands the basic usage of the file handle. The execution result of this program is the same as the CAT command of the UNIX system: #! / Usr / local / bin / perl ## programtoopenthepasswordfile, readitin, # printit, andcloseitagain. $ File = '/ etc / passwd'; # NamethefileOpen (Info, $ File); # OpenThefile @ lines =; # ieditinarrayclose (info); #closethefileprint @ line; #printtheArrayOpen function Opens a file for reading, where the first parameter is a file handle (FileHandle). The file handle is used for Perl to point to this file later. The second parameter points to the file name of the file. The Close function turns off the file.

The Open function can also be used to open the file to write and append, with only the file names before the file name> and >>: Open (INFO, $ file); # Openforinputopen (Info, "> $ file"); # Openforoutputopen (Info, ">> $ file"); # OpenForAppendingOpen (INFO, "<$ file"); # alsoopenforinput In addition, if you want to output content to a file that has been opened, you can use extra PRINT statement of the parameter. For example: PrintInfo "thislinegoestothefile."; ); # OpenStandARDOUTPUT A Perl program already has three file handles: stdin (standard input device), stdout, and stderr (standard error message output). If you want to read information from an open file handle, you can use the <> operator. Use the Read and Write functions to read and write a binary file. The usage is as follows: Read (Handle, $ Buffer, $ Length "; This command can put the file handle is the handle of the file from the file to the OFFSET, a total of $ buffer, read $ buffer. Where $ OFFSET is an option, if $ OFFSET is omitted, read () is read from the current location from the current location to the current location. You can use the following command to see if the end of the file: EOF (Handle); if a non-zero value is returned, the end of the file has been reached. Out of the file when you open a file, so you can display the error message using DIE (). Let's open a file called "Test.Data": Open (Testfile, "Test.Data") || DIE "$ 0cannotopen $!"; [Directory] --------------- -------------------------------------------------- -------------- Process Control Foreach cycle In Perl, you can use the Foreach loop to read each line in the array or other similar list structure. Please see the example below: Foreach $ morsel (@food) # visiteachiteminturn # andcallit $ msel {print "$ moryl"; #printtheitemprint "yumyum"; #thatwasnice} Every time you want to execute, the commands are crec. The value of the first element of the array @food is given the first element of the first execution, and the value of the second element of the array @food is given to the last element of the array to the last element of the array @food. Judging that any non-zero numbers and non-empty strings in Perl are considered true. Zero, all zero strings and empty strings are false. Here are some judgment operators: $ a == $ b If $ A and $ B are equal, it returns true. $ A! = $ b If $ A and $ B are not equal, return true.

$ AEQ $ B If the string is the same, the string is the same, then it returns to ane $ b If the string $ A and the string $ B are different, return true. You can use logical operators: ($ A && $ B) $ A and $ B. ($ A || $ b) $ A or $ B. ! ($ a) Non $ A. For the FOR structure in the FOR loop Perl is basically the same as: for (Initialise; Test; INC) {first_action; second_action; etc} The following is an example of a for loop, used to display numbers from 0 to 9: For ($ i = 0; $ I <10; $ i) # Startwith $ I = 1 # DOITWHILE $ I <10 # increment $ IBEFOREREPEATING {Print "$ I";} While and Until loop is a while and WHILE An example of a UNTIL loop. It reads input from the keyboard until the correct password is obtained. #! / usr / local / bin / perlprint "password?"; # askFORINPUT $ A =; # getInputchop $ a; #removethenewlineatendWhile ($ Ane "fred" # whileinputiswrong ... {print "sorry.again?"; Askagain $ a =; # getInputagainchop $ a; #chopoffnewlineagain} Execute the While loop when the input and password are not equal. You can also use While and Until at the end of the actuator, then you need to use the DO statement: #! / Usr / local / bin / perldo {"password?"; # AskFORINPUT $ A =; # getInputchop $ a; #ChopoffNewline } While ($ ANE "Fred") # redowhilewrongInput Condition Structure Perl Allow IF / THEN / ELSE expression. Please see the example below: if ($ a) {print "thistringisnotempty";} else {print "theStringiseMpty"; Note In Perl, empty characters are considered fake. Nested structure can also be used in the IF structure: IF (! $ A) #the! Isthenotoperator {print "theStringiseMpty";} elsif (Length ($ a) == 1) # ifabovefails, trythis {print "TheStringhasoneCharacter";} Elsif (Length ($ a) == 2) # ithatfails, trythis {print "theStringHastWocharacters";} else # now, everythingHasfailed {print "TheStringHASlotsOfcharacters"; [directory] ------------- -------------------------------------------------- -------------- character matching Perl character matching function is very powerful. The core of the character matching function is the rule expression (RE), which is the format involved in the character matching process. = ~ Operator is used to perform format matching and replacement.

For example: if: $ s = 'oneifylandAndtWoifBysea';: if ($ s = ~ / ifbyla /) {print "yes"} else {print "no"} will display Yes because ifbyla is in string $ s. Another example: if ($ s = ~ / one /) {print "yes"} else {print "no"} will display NO because RE is sensitive to case. If you use the I option, you will ignore the case, then Yes: if ($ s = ~ / one / i) {print "yes"} else {print "no"} listed below has many of RE Special significance: Any character except for a line break () ^ one line and a string of start $ a line and a string end *, the previous character repeat zero or multiple times its previous characters repeat one or more times The previous character repeats zero or once, for example, if ($ x = ~ / l.mp /) {print "yes"} for $ x = "lamp", "lump", "slumped" will display Yes, but Yes will not be displayed for $ x = "lmp" or "lessamperes". Look at the following example: /fr.*nd/ Match frON, Friend, FrontAck. /fr. nd/ matches Frond, Friend, FrontAck. But do not match frs. / 10 * 1 / Match 11,101,1001,100000001. / b (an) * a / matching BA, Bana, Banana, Banananana. / flo? AT / match FLAT and FLOAT, but do not match flooat. Square brackets are used to match any of the characters. In the square bracket - symbols are used to show what is in what, ^ symbols indicate not to meaning. [0123456789] Match any single number. [0-9] Match any single number. [A-Z] Match any word consisting of lowercase letters. [^ 0-9] Match any non-numeric characters. The backslash is still used for escape. If you want to match ,?,., *, ^,}, (,), [,], {,}, |,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, For example: /10.2/ Match 10q2, 1052, and 10.2. / 10.2 / match 10.2, but not 10Q2 or 1052 match. / * / Match one or more asterpanos. / A: DIR / match A: DIR. // USR / BIN / match / usr / bin. There are also some special characters below: Tabs. W No letter and numbers are the same as [A-ZA-Z0-9_]. W Any non-letter and numbers are the same as [^ A-ZA-Z0-9_]. d Any number and [0-9] are the same. D An any number of non-numbers is the same as [^ 0-9]. S any blank character: space, tab, wrap, etc. S any non-blank character. The word boundary is only valid for []. B non word boundary. Replacement Perl can use the S function to use the result of the character matching. The effect of the S function and the VI editor is basically the same. At this time, it is still using a character matching operator = ~, for example: replacing the London appearing in the String $ SENTENCE, can use the following command: $ SENTENCE = ~ S / LONDON / LONDON / command return value is made Replacement number. But this command can only replace the first London that appears. If you want to replace all London appearing in a string, you should use the / g option: S / London / London / G This command is $ _ variable, which is the current default variable.

If you want to replace a string similar to London, London, London, you can use: s / [ll] [oo] [nn] [dd] [o] [nn] / london / g but is more simple to use I option, that is, ignore the case: S / London / London / GI translation TR function allows authentication. The following command makes the A, B, and C in the string $ SENTENCE by E, F, D instead: $ SENTENCE = ~ TR / ABC / EFD / result Returns the number of replacements. Special characters in most RE do not exist in the TR function. For example, the following commands use to calculate the number of string $ SENTENCE Middle Star (*) and store the results in $ count: $ count = ($ SENTENCE = ~ TR / * / * /); [directory] --- -------------------------------------------------- ------------------------- The definition of the sub-process process can define its own sub-process. Definition of sub-processes as follows: submysubroutine {print "Notaveryinterestingroutine"; print "Thisdoesthesamethingeverytime";} The following several methods can call the subroutine: & # Callthesubroutine & mysubroutine ($ _); # Callitwithaparameter & mysubroutine (1 2, $ _); The #callitwithtwoparameters parameter calls a child process, all parameters are transmitted to the array @_. Examples of the following subsections show all parameters: Subprintargs {Print "@_";} & printargs ("Perlyprints" Perlyking & Printargs "& PrintArgs (" frog "," and "," toad ") ; #Prints "frogandToad" Return Value The following example Returns the maximum value of two input parameters: Submaximum {if ($ _ [0]> $ _ [1]) {$ _ [0];} else {$ _ [1 $ BIGGEST = & Maximum (37,24); # now $ biggestis37 [directory] ------------------------------- -------------------------------------------------example Finally, please see a complete example of a Perl language. This program generates a student grade report from a file stufile that records student information and a file scorefile recording student score.

Enter files Stufile consists of three fields of the student ID, name, and grades, separated by a semicolon: 123456; Washington, George; SR246802; Lincoln, Abraham "ABE"; SO357913; Jefferson, Thomas; JR212121; Roosevelt, Theodore TEDDY "; SO file, SCOREFILE consists of three fields of students ID, subject number, score, separated by spaces: 123456 1 98212121 1 86246802 1 89357913 1 90123456 2 96212121 2 88357913 2 92123456 3 972121 3 96246802 3 95357913 3 94 procedure should be output the following results: Stu-iDName ... 123Totals: 357913Jefferson, Thomas909294276246802Lincoln, Abraham "Abe" 8995184212121Roosevelt, Theodore "Teddy" 868896270123456Washington, George989697291Totals: 363276382 source as follows:! # / usr / local / bin / perl # Gradebook-demonstratesI / O, associative # arrays, sorting, andreportformatting # Thisaccommodatesanynumberofexamsandstudents # andmissingdata.Inputfilesare: $ stufile = 'stufile'; $ scorefile = 'scorefile'; # Iffileopenssuccessfully, thisevaluatesas "true", andPerl # doesnotevaluaterestofthe "or" "||" open. (Names, "<$ stufile") || Die "Can'topen $ stufile $!"; Open (Scores, "<$ scorefile") || Die "Can'topen $ Scorefile $!"; # BuildanassociativeArrayofstudentInfo # KeyedByStudentnumberwhile ( ) {($ Stuid, $ Name, $ Year) = Split (':', $ _); $ Name {$ stuid} = $ name; if ($ name)> $ mapNameLength) {$ mapnameLength = Length ($ name);}} closenames; #buildatablefromthetestscores: while () {($ stuid, $ examno, $ score) = split; $ score {$ stuid, $ examno} = $ score; if ($ examno> $ maxexamno) {$ maxexamno = $ examno;}} closeSCORES;! #Printthereportfromaccumulateddata printf "% 6S% - $ {maxnameLength} s",

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

New Post(0)