Perl function set

Source: Internet
Author: User
Tags chop crypt mathematical functions natural logarithm unpack

I. Process processing functions

1. Process startup Function

Function Name eval

Call the syntax eval (string)

Describe the stringPerlStatement execution.

After the command is correctly executed, the system variable $ @ is an empty string. If an error occurs, $ @ is the error message.

Example $ print = "Print (\" Hello, world \ n \");";

Eval ($ print );

Output result Hello, world

Function Name: System

Call the syntax system (list)

The first element in the list is the program name, and the rest are parameters.

System starts a process to run the program and waits for it to end. After the program ends, the error code shifts left eight bits to return values.

Example @ proglist = ("Echo", "Hello, world! ");

System (@ proglist );

Output result Hello, world!

Function Name fork

Call the syntax procid = fork ();

Describe the creation of two copies of the program-parent process and child process-run simultaneously. The child process returns zero, and the parent process returns non-zero.
Value, which is the ID of the sub-program process.

Example $ retval = fork ();

If ($ retval = 0 ){

# This is the child process

Exit; # This terminates the child process

} Else {

# This is the parent process

}

No result output

Function name pipe

Call the syntax pipe (infile, OUTFILE );

This topic explains how to use fork to communicate with Parent and Child processes. The information sent to the OUTFILE file variable can be
Read from infile variables. Steps:

1. Call Pipe

2. Use fork to divide the program into Parent and Child Processes

3. One process disables infile and the other disables 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 is the child process

Close (output );

$ Line = <input>;

Print ($ line );

Exit (0 );

}

Result output $

Program

Enter a line of input:

Here is a test line

Here is a test line

$

Function Name Exec

Call the exec (list) syntax );

Similar to system, the difference is that the current program is terminated before the new process is started. Often used with fork, when fork is divided into two
After the process, the child process starts another program with exec.

Example

Result output

Function Name: syscall

Call the syntax syscall (list );

Describe how to call a system function. The first element of the list is the system call name, and the rest are parameters.

If the parameter is a number, it is converted to the integer (type INT) of C ). Otherwise, the pointer of the string is passed. For more information, see the Unix help Perl document.

Syscall must contain the syscall. pl file, that is:

Require ("syscall. ph ");

Example

Result output

2. Process Termination Function

Function Name: Die

Call the syntax die (Message );

Describe terminate the program and output an error message to stderr. Message can be a string or a list. If the last parameter
If the number does not contain line breaks, the program file name and row number are also output.

Example die ("cannot open input file ");

Cannot open input file at myprog line 6.

Function Name warn

Call the syntax warn (Message );

The commentary is similar to die. The difference is that the program is not terminated.

Example warn ("Danger! Danger! \ N ");

Result output danger! Danger!

Function Name exit

Call the syntax exit (retcode );

Describe terminate the program and specify the return value.

Example: exit (2 );

No result output

Function Name kill

Call the syntax kill (signal, proclist );

Sends signals to a group of processes.

Signal is the digital signal sent, and 9 is used to kill the process.

Proclist is the list of process IDs. For more information, see kill's Unix help.

Example

Result output

3. Process Control Functions

Function Name sleep

Call the syntax sleep (time );

Pause the program for a period of time. Time is the number of seconds to stop. The returned value is the actual number of seconds to stop.

Example: Sleep (5 );

No result output

Function Name: Wait

Call the syntax procid = wait ();

Pause the program execution and wait for the sub-process to terminate.

No parameter is required. The return value is the sub-process ID. If no sub-process exists,-1 is returned.

Example

Result output

Function Name: waitpid

Call the syntax waitpid (procid, waitflag );

Pause the program execution and wait for the specified sub-process to terminate. Procid is the ID of the waiting process

Example $ procid = fork ();

If ($ procid = 0 ){

# This is the child process

Print ("this line is printed first \ n ");

Exit (0 );

} Else {

# This is the parent process

Waitpid ($ procid, 0 );

Print ("this line is printed last \ n ");

}

Result output $ Program

This line is printed first

This line is printed last

$

4. Other control functions

Function Name caller

Call syntax subinfo = caller ();

Returns the caller's program name and row numberPerlDebugger.

List of three elements returned:

1. Package name at the call

2. Caller's file name

3. the row number at the call

Example

Result output

Function Name chroot

Call the syntax chroot (DIR );

For details about how to change the root directory of a program, see the chroot help.

Example

Result output

Function name local

Call the syntax local ($ variable );
This topic defines local variables in statement blocks (a set of statements surrounded by braces ).
The change does not affect the variable with the same name outside the block.

Never use it in a loop. Otherwise, a new local variable is defined for each loop!

Example

Result output

Function name Times

Call syntax timelist = times

Returns the time consumed by the program and all sub-processes.

List of four floating point numbers returned:

1. User time consumed by the program

2. System Time consumed by the program

3. User time consumed by sub-Processes

4. System Time consumed by sub-Processes

Example

Result output

Ii. mathematical functions

Function Name sin

Call the syntax retval = sin (value );

The comment parameter is a radian value.

Function name cos

Call the syntax retval = cos (value );

The comment parameter is a radian value.

Function Name atan2

Call the syntax retval = atan2 (value1, value2 );

Describe the operation and return the arctan value of value1 divided by value2. Unit: radian, range:-pi ~ Pi.

Example:

Converts an angle to a radian subprogram. Sub degrees_to_radians {

Local ($ degrees) = @_;

Local ($ radians); 11:

$ Radians = atan2 (1, 1) * $ degrees/45;

}

Function Name SQRT

Call the syntax retval = SQRT (value );

Describe the square root function. Value is not negative.

Function Name exp

Call the syntax retval = exp (value );

Returns the value power of E.

Function Name Log

Call the syntax retval = Log (value );

Describe the natural logarithm Based on E.

Function Name ABS

Call syntax retval = ABS (value );

Describe the absolute value function. (Perl4)

Function Name Rand

Call the syntax retval = rand (Num );

ExplanationRandom NumberReturns a floating point number between 0 and an integer num.

Function Name srand

Call the syntax srand (value );

Commentary InitializationRandom NumberGenerator. Make sure that Rand is randomly called each time.

Iii. string processing functions

Function name index

Call the syntax position = index (string, substring, position );

Returns the position of the substring in the string. If not, returns-1. Parameter position
Is optional, indicating the number of characters that have been skipped before the match, or starting from this position.

Function Name rindex

Call the syntax position = rindex (string, substring, position );

The description is similar to the index, with the difference being matching from the right side.

Function Name Length

Call the syntax num = length (string );

Returns the length of a string, or the number of characters.

Function Name POS

Call syntax offset = pos (string );

Returns the position of the last pattern match.

Function Name substr

Call the syntax substr (expr, skipchars, length)

Describe the substring In the extracted string (or the string generated by the expression) expr, skip the skipchars character, or
This parameter indicates that the child string is extracted from the position skipchars (the first character is 0) and the length of the Child string is length.
Ignore, which means to take all the remaining characters.

When this function appears on the left side of the equation, expr must be a variable or an array element. In this case, the molecular string in the middle is on the right side of the equation.
.

Function Name Study

Call the syntax Study (scalar );

An internal format is used to increase the access speed of a variable. At the same time, it only takes effect for one variable.

Function Name LC

UC

Call the syntax retval = Lc (string );

Retval = UC (string );

Converts all strings to uppercase or lowercase letters.

Function Name lcfirst

Ucfirst

Call the syntax retval = lcfirst (string );

Retval = ucfirst (string );

The description converts the first letter into uppercase or lowercase letters.

Function Name quotameta

Call the syntax newstring = quotemeta (oldstring );

Add a backslash (\) to the front of a non-word letter (\).

Statement: $ string = quotemeta ($ string );

Equivalent to: $ string = ~ S/(\ W)/\ $1/g;

It is often used in pattern matching to ensure that no character in the string is considered as a matching operator.

Function Name join

Call the syntax join (joinstr, list );

Comments: Combine the string list (array) into a long string and insert the string joinstr between each two list elements.

Function Name sprintf

Call the syntax sprintf (string, fields );

Similar to printf, the difference is that the result is not output to the file, but is assigned to the variable as the return value.

Example $ num = 26;

$ Outstr = sprintf ("% d = % x hexadecimal or % O octal \ n", $ num );

Print ($ outstr );

Output 26 = 1a hexadecimal or 32 octal

Iv. scalar conversion functions

Function Name: Chop

Call syntax $ lastchar = chop (VAR );

Description VaR can be a variable or an array. When VaR is a variable, the last character is deleted and assigned to $ lastchar. When va
When R is an array/list, the last character of all elements is deleted, and the last letter of the last element is assigned to $ L.
Astchar.

Function Name chomp

Call syntax result = chomp (VAR );

Commentary checks whether the last character of the element in the string or string list is a line separator defined by the system variable $/
If yes, delete it. The return value is the number of characters actually deleted.

Function Name crypt

Call syntax result = crypt (original, salt );

Describe how to use the DES algorithm to encrypt strings. Original is the string to be encrypted, and salt is the string of two characters,
Defines how to change the DES algorithm to make decoding harder. The returned value is an encrypted string.

Function Name hex

Call the syntax decnum = hex (hexnum );

Converts a hexadecimal number (in string form) into a decimal number.

Function Name int

Call the syntax intnum = int (floatnum );

Converts the rounded decimal part of a floating point number to an integer.

Function Name Oct

Call the syntax decnum = OCT (octnum );

Converts an octal number (in string form) or a hexadecimal number ("0x .." form) into a decimal number.

Function Name ORD

Call syntax asciival = ord (char );

Returns the ASCII value of a single character, similar to the function of the same name in Pascal.

Function Name Chr

Call syntax $ char = CHR (asciival );

Returns the corresponding characters of the ASCII value, similar to the functions with the same name in Pascal.

Function Name pack

Call the syntax formatstr = pack (packformat, list );

The description converts a list or array
In a simple variable. The packformat parameter contains one or more format characters. Each element in the list corresponds to one,
Characters in different formats can be separated by spaces or tabs, because pack ignores spaces.

In addition to the formats A, A, and @, you can add an integer after the format is repeated multiple times. For example:

$ Twoints = pack ("I2", 103,241 );

Apply the same format to all elements with a * number, for example:

$ Manyints = pack ("I *", 14, 26, 11, 83 );

For A and A, the following integer indicates the length of the string to be created. The repeat method is as follows:

$ Strings = pack ("A6" X 2, "test1", "Test2 ");

The format @ is special. An integer must be added after it. This number indicates the length required by the string. If the length is not long enough
Is supplemented by null, for example:

$ Output = pack ("A @ 6 A", "test", "Test2 ");

The most common purpose of the pack function is to create data that can interact with the C program. For example, strings in the C language are empty characters (n
You can create such data as follows:

$ Cstring = pack ("ax", $ mystring );

The following table shows the equivalence relationship between some format characters and Data Types in C:

Character equivalent 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 complete format characters are shown in the following table.

Format Character Description

A string supplemented by null

A string supplemented by Space

B-Bit String, before Low Position

B-bit string with a high position in front

C-Signed characters (usually-128 ~ 127)

C unsigned characters (usually 8 characters)

D double-precision floating point number

F single-precision floating point number

H hexadecimal number string, low front

H hexadecimal number string with a high position in front

I-signed integer

I unsigned integer

L signed long integer

L unsigned long integer

N short integer in network order

N Network order long integer

P string pointer

S signed short integer

S unsigned short integer

Convert u to uuencode format

V vax short integer

V vax ordinal long integer

X an empty byte

X returns one byte.

@ Fill with NULL bytes

Function Name unpack

Call syntax @ list = unpack (packformat, formatstr );

The unpack function is opposite to the pack function, which converts the values stored in the machine formatPerlThe list of values. Its format characters
Similar to pack (that is, the preceding table), a format converts the machine format stringPerlRemove the string
All spaces or null characters at the end of the string; X indicates skipping one byte; @ indicates skipping some bytes to the specified position. For example, @ 4 indicates skipping.
4 bytes. Here is an example of @ and X contract: $ longrightint = unpack ("@ * X4 L", $ Pac
Kstring );

This statement converts the last four bytes into unsigned long integers. The following describes how to decode the uuencode file.
Example:

1 :#! /Usr/local/bin/Perl

2:

3: open (codedfile, "/u/janedoe/codefile") |

4: Die ("can't open input file ");

5: open (OUTFILE, "> OUTFILE") |

6: Die ("can't open output file ");

7: While ($ line = <codedfile> ){

8: $ decoded = unpack ("u", $ line );

9: Print OUTFILE ($ decoded );

10 :}

11: Close (OUTFILE );

12: Close (codedfile );

When using pack and unpack for uuencode, remember that although they work with uuencode and uuudecode in UNIX
The tool has the same algorithm, but does not provide the first line and the last line. If you want to use uudecode to import the File Created by pack output
Line decoding. the first line and the last line must also be output (for details, see the uuencode help in UNIX ).

Function Name VEC

Call the syntax retval = VEC (vector, index, BITs );

As the name implies, VEC is a vector function, which treats the value of a simple variable vector as multiple pieces of (dimension) data,
Each block contains a certain number of BITs, which together constitute a vector data. Each call accesses a piece of data and can read
. The index parameter is like an array subscript. It indicates which part to access. 0 indicates the first part, and so on,
Note that the access order is from right to left, that is, the first block is on the far right. The bits parameter specifies the number of digits in each block.
Think 1, 2, 4, 8, 16 or 32.

Example 1 :#! /Usr/local/bin/Perl

2:

3: $ vector = pack ("B *", "11010011 ");

4: $ val1 = VEC ($ vector, 0, 4 );

5: $ val2 = VEC ($ vector, 1, 4 );

6: Print ("high-to-low order values: $ val1 and $ val2 \ n ");

7: $ vector = pack ("B *", "11010011 ");

8: $ val1 = VEC ($ vector, 0, 4 );

9: $ val2 = VEC ($ vector, 1, 4 );

10: Print ("low-to-high order values: $ val1 and $ val2 \ n ");

Result: high-to-low order values: 3 and 13.

Low-to-high order values: 11 and 12

Function Name Defined

Call the syntax retval = defined (expr );

Judge whether an element of a variable, array, or array has been assigned a value. Expr is the variable name, array name, or
Array elements.

If defined, true is returned. Otherwise, false is returned.

Function Name UNDEF

Call the syntax retval = UNDEF (expr );

Describe how to cancel definitions of variables, arrays, array elements, and even subprograms and reclaim their space. The returned value is always undefined.
, Which is equivalent to an empty string.

5. array and list Functions

Function Name grep

Call the syntax @ foundlist = grep (pattern, @ searchlist );

Similar to the Unix search tool with the same name, the grep function extracts elements that match the specified pattern in the list. The parameter P
Attern is the pattern to be searched. The returned value is a list of matching elements.

Example @ list = ("this", "is", "A", "test ");

@ Foundlist = grep (/^ [TT]/, @ list );

Result @ foundlist = ("this", "test ");

Function Name splice

Call the syntax @ retval = splice (@ array, slipelements, length, @ newlist );

The commenting concatenation function can insert an element into the List (array), delete a sublist, or replace a sublist. Parameter ski
Pelements is the number of elements skipped before splicing, length is the number of elements to be replaced, newlist is to be spliced in
. When the length of newlist is greater than the length, the subsequent elements are automatically moved backward, and vice versa. Therefore,
When length = 0, it is equivalent to inserting an element into the list, which is like a statement.

Splice (@ array,-1, 0, "hello ");

Add an element to the end of the array. When newlist is empty, it is equivalent to deleting the sublist. If length is empty
Delete all elements from the skipelements column, and delete the last element as: splice (@ array,
-1); in this case, the returned value is the list of deleted elements.

Function name shift

Call the syntax element = shift (@ arrayvar );

Describe how to delete the first element of the array, move the remaining element forward, and return the deleted element. When no parameter is added @
Argv.

Function Name unshift

Call the syntax COUNT = unshift (@ arrayver, elements );

Opposite to shift, add one or more elements at the beginning of array arrayvar, and return the result (list)
. Equivalent to splice (@ array, 0, 0, elements );

Function Name push

Call the syntax push (@ arrayvar, elements );

Add one or more elements to the end of the array. Equivalent to slice (@ array, @ array, 0, elements );

Function name pop

Call the syntax element = POP (@ arrayvar );

The comment is opposite to push. Delete the last element of the list and use it as the return value. If the list is empty, return
"Undefined value" (that is, an empty string ).

Function Name split

Call syntax @ list = Split (pattern, String, maxlength );

Describe how to split a string into a list of elements. Each time pattern is matched, a new element is started, but patt
The Ern itself is not included in the element. Maxlength is optional. When it is specified, it is not separated when it reaches this length.

Function Name sort

Call the syntax @ sorted = sort (@ list );

The comments are sorted in alphabetical order.

Function Name reverse

Call the syntax @ reversed = reverse (@ list );

The comments are sorted in alphabetical order.

Function Name Map

Call the syntax @ resultlist = map (expr, @ list );

Describe this function inPerl5. Each element in the list can be used as the operand of the expression expr.
And the result is returned as the return value. In the expression expr, the system variable $ _ represents each element.

Example 1: @ list = (100,200,300 );

@ Results = map ($ _ + 1, @ list );

2. @ Results = map (& mysub ($ _), @ list );

Result 1: (101,201,301)

2. None

Function Name wantarray

Call syntax result = wantarray ();

ExplanationPerlSome built-in functions may behave differently based on their processing of simple variables or arrays, such as chop. Custom
Sub-programs can also define these two kinds of behavior. This function returns a non-zero value when the subroutine is expected to return a list.
Value (true); otherwise, the value is zero (false ).

Example 1 :#! /Usr/local/bin/Perl

2:

3: @ array = & mysub ();

4: $ scalar = & mysub ();

5:

6: Sub mysub {

7: If (wantarray ()){

8: Print ("True \ n ");

9:} else {

10: Print ("false \ n ");

11 :}

12 :}

Result $ Program

True

False

$

6. Associate array Functions

Function Name keys

Call the syntax @ list = keys (% assoc_array );

Returns the unordered subscript list of the associated array.

Function Name values

Call syntax @ list = values (% assoc_array );

Returns a list of unordered values of the joined array.

Function Name: each

Call syntax @ pair = each (% assoc_array );

Returns the list of two elements-key-value pairs (I .e. subscripts and corresponding values), which are also unordered. When the joined array is empty,
Returns an empty list.

Function Name Delete

Call the syntax element = Delete (assoc_array_item );

Describe how to delete an element from an associated array and use its value as the return value.

Example % array = ("foo", 26, "bar", 17 ");

$ Retval = Delete ($ Array {"foo "});

Result $ retval = 26;

Function name exists

Call the syntax result = exists (element );

Commentary onPerl5. determine whether an element exists in the associated array. If yes, return a non-zero value (true). Otherwise
Returns NULL (false ).

Example $ result = exists ($ myarray {$ mykey });

 

Reprinted: http://www.cnblogs.com/xinghua/archive/2007/02/06/642313.html

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.