9.1 search scalar
Search by index
Index string, substring
Index string, substring, start_position
The index function starts running from the left side of the string and searches for substring.
To the position of the substring. 0 indicates the leftmost character. If S is not found
Ubstring, index returns-1; for example:
Index "ring around the rosy", "around"; # Return 5
Index ("Pocket full of posies", "ket"); #3 is returned.
Index "DDD", "FF"; # Return-1
Index ("test", "test", 1); # Return 5
You can also use the index function with the starting position to "traverse" a character.
String to locate all the positions where a short string appears, such:
$ Source = "one fish, two fish, red fish, blue fish .";
$ Start =-1;
While ($ start = index ($ source, "fish", $ start ))! =-1 ){
Print "found a fish at $ start/N ";
$ Start ++;
}
Rindex Backward Search is basically the same as index, but it searches from right to left.
Such:
$ A = "She loves you yeah, yeah, yeah .";
Rindex ($ A, "yeah"); #26 is returned.
Rindex ($ A, "Yeah", 25); # returns 20
However, its traversal and index are a little different. Its starting point must start from the end of the character.
. Of course it is also decreasing 1 rather than adding 1, such:
$ Source = "one fish, two fish, red fish, blue fish .";
$ Start = length ($ source );
While ($ start = rindex ($ source, "fish", $ start ))! =-1 ){
Print "found a fish at $ start/N ";
$ Start --;
}
Substr separates scalar. Syntax:
Substr string, offset
Substr string, offset, Length
The substr function extracts the string, starts running from the position offset, and returns the string from the off
The rest of the string from set to the end. If length is set
Length indicates the character, or until the end of the string is found, first served
Accurate, such
$ A = "I do not like green eggs and ham .";
Print substr ($ A, 25); # output and ham.
Print substr ($ A, 14,5); # output green"
If offset is a negative value, the substr function starts counting from the right side, such as substr (
$ A,-4) returns the last 4 characters of $ A. If length is negative, substr returns
Returns the value from its start point to the end of the string, as shown in figure
Print substr ($ A, 5,-10); # output not like green egg
You can also use the substr function on the left of the value assignment expression.
STR indicates which characters of a scalar will be replaced.
Edge, the first parameter of substr must be a value that can be assigned a value, such as a scalar
Variable instead of a string, as shown below:
$ A = "countrymen, lend me your wallets ";
# Replace the first letter with "n3tl04d, C"
Substr ($ A, 0, 1) = "n3tl04d, C ";
# Insert "BL ,"
Substr ($ A, 0, 0) = "BL ,";
# Replace the last 7 characters
Substr ($ A,-7,7) = "ears .";
Tr // (Y //) Conversion operator. Syntax:
TR/searchlist/replacementlist/
Example
TR/ABC/XYZ/; # In $ _, change ABC to XYZ
$ R = ~ TR/ABC/XYZ/; # is the same, just use $ R
TR/A-Z/a-z /;
If the replacementlist is empty or is the same as the searchlist, tr
/// Calculate and return matched characters. The target string is not modified, for example:
$ Potato = "dldii ";
$ Eyes = $ potato = ~ TR/I //;
# Calculate the number of I in $ potato and return $ eyes. Here is 2.
$ Nums = TR/0-9 //; # calculates the number in $ _ and returns it to $ nums. Here it is 0.
The syntax of printf is as follows:
Printf formatstring, list
Printf filhandle formatstring, list
Formatstring is a string describing the output format, and list is a string you want
Lists the values displayed by printf.
%-W. dx
Explanation:
% Domain qualifier mark
-If there is a minus sign (optional), the output is left aligned.
Total Width of W domain (required)
. Decimal point (optional)
D. number of digits after the decimal point (optional)
X domain type (required) the hyphen before the X operator indicates that the domain is in the W string.
Left alignment; otherwise, it is right alignment.
Only % and X are indispensable. Some data (fields) types are as follows:
C character
S string
D: A decimal integer that truncates the decimal digits.
F floating point number
Some examples:
Printf ("% 20 s", "Jason"); # "Jason"
Printf ("%-20 s", "small"); # Left-aligned output "small"
$ AMT = 7.12;
Printf ("% 6.2f", $ AMT); # output "7.12"
$ Amt1 = 7.127;
Printf ("% 6.2f", $ amt1); # output "7.13"
Printf ("% C", 65); # output "A" ASCII code
$ Amt2 = 9.4;
Printf ("% 6.2f", $ amt2); # output "9.40"
Printf ("% 6D %", $ amt2); # Enter "9"
You can also
Printf ("% 6D % 4C", $ A, $ B );
9.5 stack form
Push target_array to push the project to the stack
Pop target_array, new_list to retrieve the project from the top of the stack
Shift target_array extracts elements from the bottom
Unshift target_array, new_list add elements to the bottom of the stack
Note that the bottom of the stack is element 0, and the top of the stack is the last element in the array.
Example:
@ Band = QW (trombone );
Push @ band, QW (ukulele clarinet );
# @ Band contains trombonem, ukulele, and clarinet
$ Brass = shift @ band; # Remove trombone from the bottom
$ Wind = pop @ band; # Remove clarinet from the top
# Now @ band only has ukulele
Unshift @ band, "harmonica"; # Add harmonica from the bottom
The splicing function splice syntax is as follows:
Splice array, offset
Splice array, offset, Length
Splice array, offset, length, list
Splice is used to delete the elements in the array starting from the offset position and return
Element of the deleted array. If offset is a negative value, it starts from the end of the array.
If length is set, only the elements specified by length are deleted.
If list is set, the specified element is deleted and replaced with the list element. For example:
@ Veg = QW (carrots corn );
Splice (@ veg, 0, 1); # @ veg is corn
Splice (@ veg, 0, 0, QW (peas); # @ veg is peas, corn
Splice (@ veg,-1,-1, QW (Barley, turnip); # veg is
Peas, barley, turnip
Splice (@ veg, 1, 1) # @ vegis peas, turnip
10. Files And Directories
Retrieve directory list Functions
Opendir dirhandle, directory;
Directory handle dirhandle should all use uppercase letters
Readdir dirhandle; read its content
Closedir dirhandle; Disable
The following is an example of reading a directory that does not contain... and.
Opendir (test, '/') | die "cannot open/: $! ";
@ Files = grep (! /^ /./.? $/, Readdir test); # Remove... and.
Closedir (test );
To find all files with a specific extension, you can use:
@ Ffiles = grep (//. txt $/I, readdir (test );
Note: The file name returned by readdir does not contain the path used by opendir.
The following example may fail to run:
Opendir (test, '/test') | die "cannot open/: $! ";
While ($ file = readdir test)
Open (fileh, $ file) | "cannot open $ file: $! /N ";
}
Should be changed to open (fileh, "/test/$ File") | "cannot open
$ File: $! /N ";
Another way to read a directory is to use globbing. The syntax is as follows:
Glob Pattern
Pattern is the file name pattern you want to match
Character matching mode example
? Single Character F? D is used to match fud, FID, and FDD.
* Any number of characters f * D are used to match FD, FDD, and food.
[Chars] Any chars f [ou] D is used to match fod and fud
{A, B,} A or B f * {txt, Doc} matches
File ending with Doc
Create and delete directories
Mkdir newdir, permissions; create a directory. If the directory is successfully created, true is returned. Otherwise
Return false, and set $! Set it to the cause of mkdir failure. For example:
Print "directory to create? ";
My $ newdir = <stdin>; chomp $ newdir;
Mkdir ($ newdir, 0755) | die "failed to create
$ Newdir: $! ";
Rmdir pathname; delete a directory
Unlink list_of_files; deleting a file unlink can delete list_of_files
And returns the number of deleted files. If list_of_fil
ES is omitted. The file specified in $ _ will be deleted. Check whether the file list has been deleted.
The number of files to be deleted and the number of deleted files must be
Comparison:
My @ files = <*. txt>;
My $ erased = unlink @ files;
# The number of deleted files is stored in $ erased.
If ($ erased! = @ Files) {# Compare with the number of @ files elements,
Print "files failed to erase :",
Join (',', <*. txt>), "/N"; # different, no output
Deleted file
}
Rename oldname, newname;
Rename the file. If only the path is set, rename will remove the file from a directory.
To another directory.
Chmod mode, list_of_files; change the permission, which is only useful in UNIX, as shown in figure
Chmod 0755, 'test. pl ';
11. interoperability between systems
1. the syntax of the system () function is as follows:
System Command; output cannot be captured, for example:
System ("DIR/W ");
To start a graphic file editor:
System ("notpad.exe test.txt ");
2. Capture output
Any commands enclosed by quotation marks ('') can be used as external commands.
The output is captured and used as the inverse
The return value of quotation marks, for example:
$ Directory = 'dir'; # Run the Dir command
Another way to replace the quotation marks is to use QX {}.
Use QX <>, qx (), QX [], for example:
$ Perldoc = QX {perldoc pero };
Code portability
View directory Space
My (@ Dir, $ free );
@ Dir = 'dir ';
$ Free = $ dir [$ # dir];
$ Free = ~ S/. * ([/d,] +)/W + free/$1 /;
$ Free = ~ S/, // G;
Operating System judgment
If ($ ^ o EQ 'mswin32 '){
# Execute the code in the window
} Elseif ($ ^ o EQ 'linux '){
# CMB Linux code
}
12. Nothing
XIII. References and structures
References are somewhat like pointers, such
$ Ref =/$ A; # create a reference to $
$ Ref does not contain any data used for it. It is just a reference to $.
. To output the value of $ A through $ Ref, you can use:
Print $ ref;
If you modify the original value through reference, you can use:
$ Ref = "sticks ";
The same is true for Array references.
$ Aref = // @ arr;
$ Aref [0] @ the first element of ARR, or $ {$ Aref} [0]
@ $ Aref [2, 3] @ arr
@ $ Aref @ the entire array of ARR
References to the hash structure
$ Href/% hash;
$ Href {key}
Access a keyword in % hash, which can also be $ {$ href} {key}
% $ Href can access the entire hash structure, or % {$ href}
To iterate through the hash structure and output all values, you can use:
Foreach $ key (Keys % $ href ){
Print $ href {key };
}
Reference as a parameter
Structure
Perl does not support two-dimensional arrays, but can use arrays, such:
@ List_of_lists = (
[QW (11 12 13)],
[QW (21 22 23)],
[QW (31 32 );,
);
$ List_of_lists [0] [1]; #11
You need to know the number of elements in the outermost list:
$ # List_of_lists; # the last one is two elements.
Scalar (@ list_of_lists); # the number of rows is three.
To traverse the list, use the following code:
Foreach my $ outer (@ list_of_lists ){
Foreach my $ inner (@ {$ outer }){
Print "$ inner ";
}
Print "/N ";
}
You can add the following structure:
Push (@ list_of_lists, [QW (41 42 43)]); # Add a row
Push (@ {$ list_of_lists [0]}, QW (14); # Add a new one in the first line
Element
14. Use of modules
The rest is similar to the instructions.
Simplest Ping
#! /Usr/bin/perl-W
Use strict;
Use Net: Ping;
If (pingecho ("www.163.com", 15 )){
Print "163 is on the network .";
} Else {
Print "163 is unreacheable .";
}
The diagnostics module helps you find errors in the program.
Related Websites
Www.cpan.org
15. Understand program running performance
1. DBM File
DBM files are files that have been connected to a Perl hash structure. To read
To retrieve and write dBm files, you only need to operate on a hash structure, such:
Dbmopen (hash, filename, Mode)
The provided filename actually creates two different files on the hard disk, that is, filna
Md. PAG and filename. dir, but not a text file. For a Linux system,
Generally, mdoe is 0664. Example:
Dbmopen (% hash, "dbmfile", 0664) | die "can't open dBm
Dbfile: $! ";
$ Hash {feline} = "cat ";
$ Hash {canine} = "dog"; # assign a value
Print $ hash {canine}; # retrieve
Dbmclose (% hash); # Close the connection
Note:
· The length of keywords and data is limited. Although the hash structure is not limited, keywords and
Data combination cannot exceed 1024 bytes
· All values in the hash structure before running dbmopen are lost. It is best to use only the new
As follows:
% H = ();
$ H {dromedary} = "Camel ";
Dbmopen (% H, "Database", 0664) | die "cannot open: $! ";
Print $ H {dromedary}; # The output is empty.
Dbmclose (% H );
· After the dbmopen function is executed, the value of the hash structure will be
Disappear:
Dbmopen (% H, "Database", 0664) | die "cannot open: $! ";
$ H {dromedary} = "Camel ";
Dbmclose (% H );
Print $ H {dromedary}; # The output is empty.
Traversal
Dbmopen (% RECs, "records", 0664) | die "cannot open: $! ";
While ($ key, $ value) = each % RECs ){
Print "$ key = $ value/N ";
}
Dbmclose (% RECs );
15. The object is locked for read/write errors.
Use fcntl QW (: flock );
Flock (filehandle, lock_type );
Lock_type can use the following values:
· The lock _ SH value requires the public lock to be set on the file.
· The lock _ ex value requires you to set
Dedicated lock
· The lock _ UN value is used to release a lock and is rarely used.
For example, the input/output of a text file is locked.
#! /Usr/bin/perl-W
Use strict;
Use fcntl QW (: flock );
My $ semaphore_file = "/tmp/list154.sem ";
# General Lock Functions
Sub get_lock {
Open (SEM, "> $ semaphore_file") | die "cannot
Create semaphore: $! ";
Flock (SEM, lock_ex) | die "lock failed: $! ";
}
# General unlock Functions
Sub release_lock {
Close (SEM );
}
Sub readdata {
Open (pH, "phone.txt") | die "can't open
Phone.txt $! ";
My (@ data) = <pH>;
Chomp (@ data );
Close (ph );
Return (@ data );
}
Sub writedate {
My (@ data) = @_;
Open (pH, "> phone.txt") | die "can't open
Phone.txt $! ";
Foreach (@ data ){
Print pH "$ _/N ";
}
Close (ph );
}
My @ phonel;
Get_lock ();
@ Phonel = readdata ();
Push (@ phonel, "n3tl04d 12345678 ");
Writedate (@ phonel );
Release_lock ();
SleepProblems
When writing a shell program, you often wantSleepFor a period of timeSleepThe minimum unit of time for a command is second. Sometimes it cannot meet our precision requirements. This can be calledPerlTo achieve the goal.
Perl-E 'select (UNDEF, 0.001 );'
AboveSleep0.001 seconds, that is, 1Millisecond, The select function can be accurate to at least 0.000001, that is, 1 subtle