Perl function Set Summary _perl

Source: Internet
Author: User
Tags error code eval natural logarithm ord sin sorts sprintf square root

Process processing functions

1. Process Start function

Function name Eval

Call Syntax eval (string)
The commentary considers a string as a Perl statement execution.
When executed correctly, the system variable $@ is an empty string, and if there is an error, $@ is an error message.
Example $print = "print" (\ "hello,world\\n\"); ";
eval ($print);
Results Output Hello, world

Function Name System

Calling syntax System (list)
The first element in the explanation list is the program name, and the remainder is a parameter.
System starts a process to run the program and waits for it to end, and the error code moves left eight digits to the return value after the program finishes.

Example @proglist = ("echo", "hello,world!");
System (@proglist);
Results Output Hello, world!

Fork of Function name

Call Syntax ProcID = fork ();
Explains the two copies of the creation program--The parent and child processes--running at the same time. The child process returns zero, and the parent process returns a Non-zero
Value, which is the process ID number of the subroutine.
Example $retval = fork ();
if ($retval = = 0) {
# This are the child process
Exit # This terminates the child process
} else {
# This is the parent process
}
Results Output No

Pipe of function name

Call Syntax pipe (infile, outfile);
The narration is shared with fork, providing a way for the parent process and the subprocess to communicate. The information sent to the outfile file variable can be
Read by infile file variable. Steps:
1, call Pipe
2, use fork to divide the program into the parent process and the child process
3. One process turns off infile and the other turns off outfile
Example pipe (INPUT, OUTPUT);
$retval = fork ();
if ($retval!= 0) {
# This is the parent process
Close (INPUT);
Print ("Enter a line of input:\n");
$line = <STDIN>;
Print OUTPUT ($line);
} else {
# This are the child process
Close (OUTPUT);
$line = <INPUT>;
Print ($line);
Exit (0);
}

Result output $
Program
Enter a line of input:
This is the a test line
This is a test number
$

function name exec

invokes the syntax exec (list); The
narration is similar to system, except that the current program is terminated before a new process is started. Often combined with fork, when Fork is divided into two
processes, the subprocess starts another program with exec.
Example    
Results output   

function name Syscall

Call Syntax Syscall (list); The
narration calls the system function, the first element of the list is the system call name, and the remainder is a parameter. The
If the parameter is a number, the integer (type int) that is converted to C. Otherwise, a pointer to the string is passed. See the UNIX Help Perl documentation for details.
Use syscall must include file syscall.pl, that is:
require ("syscall.ph"); 
Example   
result output   
2, The process termination function

functions name die

invokes the syntax die (message); The
explains the termination of the program and outputs an error message to the stderr. The message can be a string or a list. If the last parameter
number does not contain a newline character, the program file name and line number are also exported.
Example Die ("Cannot open input file");
Result output cannot open input file at Myprog Line 6. The

function name warn

invokes the syntax warn (message); The
narration is similar to die, except that the program is not terminated.
Example warn ("danger! Danger!\n ");
Result Output danger! danger!

Function name exit

Call syntax exit (RETCODE);
Explains the termination of the program and specifies the return value.
Example exit (2);
Results Output No

function name of Kill

Call syntax Kill (signal, proclist);
Explanation sends a signal to a set of processes.
Signal is the digital signal sent, 9 for the kill process.
ProcList is a list of process IDs. Refer to the UNIX Help for Kill.
Example
Result output

3. Process Control function

function name of sleep

Call Syntax sleep (time);
The commentary pauses the program for some time. Time is the number of seconds to stop. The return value is the number of seconds that are actually stopped.
Example sleep (5);
Results Output No

The name of the letter wait

Call Syntax ProcID = Wait ();
The commentary pauses the program execution and waits for the child process to terminate.
No arguments are required, the return value is a subprocess ID, and if there are no child processes, return-1.
Example
Result output

The

function name Waitpid

invokes the syntax Waitpid (PROCID, Waitflag); The
Commentary suspends program execution and waits for a specific subprocess to terminate. ProcID for the waiting process ID
Example $procid = Fork ();
if ($procid = = 0) {
  # This are the child process
  print (' This ' is printed first\n ');
  Exit (0);
} else {
  # This is the parent process
  Waitpid ($procid, 0);
  Print ("This is printed last\n");
}
Results Output $ program
"This" is printed the "This" is printed the last
$

4. Other control functions

Caller of Function name

Call Syntax Subinfo = caller ();
EXPLANATION returns the caller's program name and line number for use in Perl Debugger.
Returns a list of ternary values:
1, the name of the package at the call
2, caller name
3, the line number at the call
Example
Result output

Chroot of Function name

Call Syntax Chroot (dir);
Explain change the root directory of the program, see Chroot Help.
Example
Result output

function Name of Local

Call syntax local ($variable);
The explanation defines a local variable in the statement block (a collection of statements surrounded by braces) and works only in this statement block, which
Change does not affect the variable with the same name outside the block.
Do not use in the loop, otherwise each cycle will define a new local variable!
Example
Result output

function name times

Call Syntax Timelist = times
EXPLANATION returns the working time consumed by the program and all child processes.
Returns a list of four floating-point numbers:
1, the user time consumed by the program
2, the program consumption of the system time
3. User time consumed by the child process
4, the child process consumption of the system time
Example
Result output

Second, the mathematical function

Letter of the name Sin

Call Syntax retval = sin (value);
The explanation parameter is a radian value.

function name cos

Call syntax retval = cos (value);
The explanation parameter is a radian value.

Atan2 of Function name

Call Syntax retval = atan2 (value1, value2);
The explanation operation and returns the Value1 divided by the value2 result arctan value, in radians, in the range of-PI~PI.
application Example:
Angle into radians subroutine. Sub Degrees_to_radians {
Local ($degrees) = @_;
Local ($radians); 11:
$radians = atan2 (1,1) * $degrees/45;
}


sqrt of function name

Call syntax retval = sqrt (value);
Explanation square root function. Value is not a negative number.


Letter of the name exp

Call Syntax retval = exp (value);
The explanation returns the value of E.


Log of Function name
Call syntax retval = log (value);
Explain the natural logarithm with e as the base.


Function name ABS
Call Syntax retval = ABS (value);
Explains the absolute value function. (Not in Perl 4)


Function name Rand
Call Syntax retval = rand (num);
Explains the random number function, which returns a float between 0 and integer num.


Srand of Function name
Call Syntax Srand (value);
Explains the initialization of random number generators. Guarantee that Rand is truly random every time it calls.


Third, string processing functions

function name of index
Call Syntax position = index (string, substring, position);
The narration returns the position of the substring substring in string strings, or returns 1 if it does not exist. Parameter position
is an optional option that represents the number of characters skipped before the match, or the start of a match from that location.


Rindex of Function name
Call syntax position = Rindex (string, substring, position);
The explanation is similar to index, except that it matches from the right side.


Length of function name
Call Syntax num = length (string);
EXPLANATION returns the length of the string, or the number of characters it contains.

Function Name Pos
Call Syntax offset = pos (string);
EXPLANATION returns the position of the last pattern match.

substr of function name
Call Syntax substr (expr, skipchars, length)
Explanation Extract string (or string generated by expression) a substring in expr, skip skipchars characters, or
Skipchars begins to extract the substring from the position (the first character position is 0), and the substring length, which can be
Ignore, meaning to take all the remaining characters.
When this function appears to the left of the equation, expr must be a variable or an array element, where some of the substrings are on the right side of the equation
Replaces the value.

Study of function name
Call syntax study (scalar);
The explanation uses an internal format to improve the access speed of a variable, and at the same time it works on only one variable.

Function name LC
Uc
Call Syntax retval = LC (String);
retval = UC (string);
Explanation converts the string into small/uppercase letters.

Lcfirst of function name
Ucfirst
Call Syntax retval = Lcfirst (string);
retval = Ucfirst (string);
The explanation converts the first letter to small/uppercase.

Quotameta of function name

Call Syntax newstring = Quotemeta (oldstring);
The narration adds a backslash (\) to the front of a letter that is not a word.
Statement: $string = Quotemeta ($string);
Equivalent to: $string =~ s/(\w)/\\$1/g;
Often used in pattern matching operations, ensure that no characters in the string are treated as matching operators.

Function name Join

Call syntax Join (JOINSTR, list);
The narration combines a string list (array) into a long string, inserting a string of joinstr between each of the two list elements.

sprintf of Function name

Call Syntax sprintf (string, fields);
The explanation is similar to printf, except that the result is not output to a file, but is assigned to a variable as a return value.
Example $num = 26;
$outstr = sprintf ("%d =%x hexadecimal or%o octal\n", $num, $num, $num);
Print ($OUTSTR);
Result output = 1a hexadecimal or octal

Scalar conversion function

Chop of Function name

Call Syntax $lastchar = Chop (VAR);
EXPLANATION var can be a variable or an array, and when Var is a variable, the last character is deleted and assigned to $lastchar, when VA
R an array/list, the last character of all elements is deleted, and the last letter of the last element is assigned to the
Astchar.

Chomp of Function name

Call syntax result = Chomp (Var);
Explanation checks whether the last character of the element in a string or string list is a row delimiter defined by the system variable $/
, if it is deleted. The return value is the number of characters actually deleted.

Crypt of Function name

Call syntax result = Crypt (original, salt);
Explanation uses the DES algorithm to encrypt the string, original is the string that will be encrypted, the salt is a two-character string,
Defines how to change the DES algorithm to make it more difficult to decode. The returned value is the encrypted string.

Hex of Function name

Call Syntax Decnum = Hex (hexnum);
The explanation converts the hexadecimal number (the string form) to a decimal number.

function name int

Call syntax intnum = int (floatnum);
The explanation converts the floating-point number to an integer.

Function name Oct

Call Syntax Decnum = Oct (octnum);
The narration will octal number (string form) or hexadecimal number ("0x ..." form) into a decimal number.

Ord of Function name

Call Syntax Asciival = ord (char);
The explanation returns the ASCII value of a single character, similar to a function of the same name in Pascal.

Chr of function name

Call Syntax $char = chr (asciival);
EXPLANATION returns the corresponding character of the ASCII value, similar to the function in Pascal with the same name.

Function Name Pack

Call Syntax Formatstr = Pack (Packformat, list);
To transform (wrap) a list or array into a format used in a programming language such as a real machine storage format or a C.
In a simple variable. The parameter Packformat contains one or more format characters, one for each element in the list,
Each format character can be separated by spaces or tabs because the pack ignores spaces.
In addition to formatting A, a, and @, reuse a format multiple times to add an integer later, such as:
$twoints = Pack ("I2", 103, 241);
Apply the same format to all elements by adding a * number, such as:
$manyints = Pack ("i*", 14, 26, 11, 83);
For A and a, the following integer represents the length of the string to be created, and the Repeat method is as follows:
$strings = Pack ("A6" x 2, "Test1", "test2");
The format @ is special and must be followed by an integer that indicates the length of the string, if not enough
, it complements the null character (null), such as:
$output = Pack ("A @6 a", "Test", "test2");
The most common use of a pack function is to create data that can interact with a C program, such as a string with a null character in the C language (n
ULL) end, creating such data can be done by:
$Cstring = Pack ("ax", $mystring);
The following table is the equivalence relationship between some format characters and the data types in C:

Character     equivalence C data type
C char
D double
F float
I int
I unsigned int (or unsigned)
L long
L unsigned long
s short
s unsigned short

The full format characters are shown in the following table.

Format character description
A string that is filled with a null character (NULL)
A string made up of spaces
B-bit string, low in front
B-bit string, high in front
C Signed characters (usually -128~127)
C unsigned characters (usually 8-bit)
D double-precision floating-point number
F single-precision floating-point numbers
h hexadecimal number string, low in front
H hexadecimal number string, high in front
I signed integer
I unsigned integers
L Signed Long Integer
L unsigned long integer
n Network sequence Short integer
N Network ordinal Long Integer
P string pointer
s signed short integer
S unsigned short integer
U convert to uuencode format
V VAX sequence Short integer
V Vax ordinal Long Integer
X an empty byte
X Rewind One Byte
@ empty byte (null) padding

Unpack of Function name

Call Syntax @list = unpack (Packformat, formatstr);
Narrator unpack in contrast to pack functionality, converts values stored in machine format into a list of values in Perl. Its format characters
Basically the same as the pack (that is, the table above), unlike the following: A format converts machine format strings into Perl strings and removes
Trailing all spaces or null characters; X is skipping a byte; @ is skipping some bytes to a specified location, such as @4 for skipping
4 bytes. Here's an example of a @ and an x contract: $longrightint = Unpack ("@* X4 L", $pac
kstring);
This statement converts the last four bytes as unsigned long integers. Here's a look at a decoding of the Uuencode file
Example:

Copy Code code as follows:

#!/usr/local/bin/perl

Open (Codedfile, "/u/janedoe/codefile") | |
Die ("Can ' t open input File");
Open (outfile, ">outfile") | |
Die ("Can ' t open output file");
while ($line = <CODEDFILE>) {
$decoded = Unpack ("U", $line);
Print outfile ($decoded);
}
Close (outfile);
Close (Codedfile);


When using packs and unpack for uuencode, keep in mind that although they are related to Uuencode, UUDecode
The tool algorithm is the same, but does not provide the first and last lines, if you want to use UUDecode to enter the file created by the pack's output
Line decoding, the first and last lines must also be output (see Uuencode Help in Unix).

VEC of Function name

Call Syntax retval = VEC (vector, index, bits);
As the name suggests, VEC is a vector function that regards the value of a vector of simple variables as multiple (dimensional) data.
Each block contains a certain number of bits, which together is a vector data. Each call accesses one piece of data and can be read
, or write to. Parameter index is like an array subscript, which one is accessed, 0 is the first block, and so on,
Note that the access order is from right to left, that is, the first block is on the far right. Parameter bits specifies the number of digits in each block, and can be
Thought 1,2,4,8,16 or 32.

Example

Copy Code code as follows:

#!/usr/local/bin/perl

$vector = Pack ("b*", "11010011");
$val 1 = VEC ($vector, 0, 4);
$val 2 = VEC ($vector, 1, 4);
Print ("High-to-low Order values: $val 1 and $val 2\n");
$vector = Pack ("b*", "11010011");
$val 1 = VEC ($vector, 0, 4);
$val 2 = VEC ($vector, 1, 4);
Print ("Low-to-high Order values: $val 1 and $val 2\n");
Results High-to-low order Values:3 and 13
Low-to-high Order Values:11 and 12

defined of Function name

Call syntax retval = defined (expr);
The explanation determines whether an element of a variable, array, or array has already been assigned a value. Expr is a variable name, an array name, or a
The array element.
Returns true if it is defined, otherwise returns false.

undef of function name

Call Syntax retval = undef (expr);
Explanation cancels the definition of a variable, array, or array element, or even a subroutine, and reclaims its space. The return value is always an indeterminate value
, this value is equivalent to an empty string.

v. Array and list functions

Function name grep
Call Syntax @foundlist = grep (pattern, @searchlist);
Explanation similar to the UNIX lookup tool with the same name, the grep function extracts the element in the list that matches the specified pattern, and the parameter P
Attern for the pattern you want to find, the return value is a list of matching elements.
Example @list = ("This", "is", "a", "test");
@foundlist = grep (/^[tt]/, @list);
The result @foundlist = ("This", "test");

Splice of Function name

Call Syntax @retval = Splice (@array, slipelements, length, @newlist);
The narration concatenation function can insert an element into the middle of a list (array), delete a child list, or replace a child list. Parameter ski
Pelements is the number of elements skipped before stitching, length is the number of elements to be replaced, NewList is going to be spliced in
The list. When the length of the newlist is greater, the following elements are automatically moved backward and the reverse is indented forward. So
When length=0, it is equivalent to inserting an element into the list, and the form is like a statement
Splice (@array,-1, 0, "Hello");
Adds an element to the end of the array. When NewList is empty, it is equivalent to deleting the child list, and if length is null
, remove all from the first skipelements element, and delete the last element: Splice (@array,
-1); In this case, the return value is the list of deleted elements.

Function Name shift
Call syntax element = Shift (@arrayvar);
EXPLANATION Delete the first element of the array, leaving the element forward and returning the deleted element. When you do not add arguments, you default to the @
argv the operation.

Unshift of function name

Call Syntax count = unshift (@arrayver, elements);
The explanatory action is the opposite of shift, adding one or more elements at the beginning of the array Arrayvar, and the return value is the result (list)
The length. Equivalent to splice (@array, 0, 0, elements);

function Name of push

Call syntax push (@arrayvar, elements);
Explanation adds one or more elements to the end of an array. Equivalent to Slice (@array, @array, 0, elements);

Function name Pop

Call syntax element = pop (@arrayvar);
Explanation vs. push action, delete the last element of the list and use it as the return value, and when the list is empty, return
"Undefined value" (that is, empty string).

function name of Split

Call Syntax @list = Split (pattern, String, maxlength);
An explanation splits a string into a list of elements. Each match once pattern, starts a new element, but Patt
The ern itself is not included in the element. MaxLength is optional, and when it is specified, the length is no longer split.

Function name Sort

Call Syntax @sorted = sort (@list);
The narration sorts the list alphabetically.

Reverse of Function name

Call Syntax @reversed = reverse (@list);
The narration sorts the list by alphabetical order.

Function name Map

Call Syntax @resultlist = map (expr, @list);
To explain this function as defined in PERL5, you can manipulate the individual elements in the list as operands of expression expr
, which does not change itself, the result being the return value. In expression expr, the system variable $_ represents each element.
Example 1, @list = (100, 200, 300);
@results = Map ($_+1, @list);
2, @results = Map (&mysub ($_), @list);
Results 1, (101, 201, 301)
2, no

Wantarray of Function name

Call syntax result = Wantarray ();
In Perl, some of the built-in functions behave differently depending on whether they are dealing with simple variables or arrays, such as chop. Self-determined
A righteous subroutine can also define two types of behavior. This function returns a Non-zero value when the subroutine is expected to return to the list
Value (TRUE), otherwise it is a zero value (false).
Example

Copy Code code as follows:

#!/usr/local/bin/perl

@array = &mysub ();
$scalar = &mysub ();

Sub MySub {
if (Wantarray ()) {
Print ("true\n");
} else {
Print ("false\n");
}
}

Results $program
True
False
$

Vi. Associative array functions

function name Keys

Call syntax @list = keys (%assoc_array);
EXPLANATION Returns an unordered list of subscript for the associative array.

Number of functions name values

Call Syntax @list = VALUES (%assoc_array);
EXPLANATION Returns a list of the unordered values of the associative array.

The

function name each

invokes the syntax @pair = each (%assoc_array); The
narration returns a list of two elements-the key-value pair (that is, the subscript and the corresponding value), equally unordered. When the associative array is empty,
returns an empty list.

Function name Delete

Call syntax element = delete (Assoc_array_item); The
illustration deletes an element from an associative array and takes its value as the return value.
Example%array = ("foo", "Bar", "17");
$retval = delete ($array {"foo"});
Result $retval = 26;

function name exists

call syntax result = exists (element); The
explanation is defined in PERL5, determines whether an element exists in the associative array, returns a value other than 0 (true) if it exists, or
returns a value of 0 (false).
Example $result = exists ($myarray {$mykey});

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.