Here are the Perl functions, listed alphabetically.
abs VALUE
Returns the absolute value of VALUE. VALUE can be a number (such as -7), or an expression (such as int(5/2)).
accept NEWSOCKET, GENERICSOCKET
accept is used to accept an incoming socket connection. If the connection is successful, the packed address is returned, otherwise, FALSE is returned. Identical to the accept(2) system call.
alarm SECONDS
The alarm function sends a SIGALRM to the program after the number of seconds specified in SECONDS has elapsed. Only one timer can be running at a time, so if you call this function and a timer is already running, it will be replaced by the more recent call. Calling this function with an argument of 0 will suspend the current timer without starting a new one. If SECONDS is not specified, the value in $_ is used.
atan2 Y, X
Returns the arctangent of Y/X in the range -p to p. Functions for the tangent operation are in the POSIX and Math::Trig modules.
bind SOCKET, NAME
The bind function binds a network address to a socket. NAME should contain the packed address for that type of socket. If the bind function is successful, it returns TRUE, otherwise it returns FALSE. Identical to the bind system call.
binmode FILEHANDLE
binmode accepts a filehandle as an argument, and indicates that data should be written to (or read from) the filehandle as binary, as opposed to ASCII, data. It has no effect under Unix, but is critical under MS-DOS and other archaic platforms. It should be called after a file is opened, but before any I/O is performed on that file.
bless REFERENCE, CLASSNAME
bless is used in object-oriented Perl programming to assign whatever is referenced by REFERENCE to the package named by CLASSNAME. If CLASSNAME is omitted, REFERENCE is assigned to the current package. bless returns the reference being blessed. Usually to create an object you bless an anonymous hash. For detailed information check out the perlobj man page.
caller EXPR caller
caller returns the context of the current subroutine call. In the scalar context, caller returns the package name from which the subroutine was called; in the list context, it returns the package name, filename of the program, and line number from which the call was issued. If EXPR is supplied, caller also returns extra information used to print a stack trace. EXPR indicates how many call frames to go back before the current one. When EXPR is supplied, the following list of values is returned:
($package, $file, $line, $subname, $hasargs, $wantarray, $evaltext, $is_require, $hints, $bitmask) = caller(any_func);
If called from within the DB package, caller also sets the variable @DB::args to the arguments passed to the given stack frame.
chdir EXPR
chdir accepts an expression as an argument, and attempts to set the current directory to the directory supplied by the expression. If no argument is provided, it attempts to change to the home directory for the current user.
chmod LIST
chmod is used to change the file permissions for the list of files provided in LIST. The first element of LIST must be the numerical mode for the files, in octal notation. It should also include the SUID bit. Here's an example of the usage of chmod:
chmod 0755, @files;
Note that the first element of the list is not enclosed within quotation marks, it is a bare number. For more information on file permissions, see the chmod man page.
chomp VARIABLE chomp LIST chomp
chomp is a safe version of chop, which is described next. It removes any line ending that matches $/ (the variable that contains the input record separator, usually a newline). If it is called in paragraph mode, it removes all the trailing newlines from a string.
chop VARIABLE chop LIST chop
chop is used to remove the last character from a string. Originally it was designed to make it easy to strip the line feed from the end of a string (when you're editing a file line by line, it often makes sense to remove the line feeds from the lines before you start working on them). The problem with chop is that it removes the last character from the string regardless of what it is, so if the string ends with a line feed, great, but if it doesn't you lose the last character, which might have been meaningful.
while (<INPUT_FILE>) { # Note that in this example, $_ is assumed to be the argument to # the chomp function. chop; push (@names); }
If no argument is supplied to chop, it removes the last character from $_. If a list is supplied, the last character in all the items in the list is removed.
chown LIST
chown is used to set the user and group ownership for files provided in LIST. It returns the number of files that were successfully changed. The first two elements of LIST must be the numerical uid and gid of the user and group, which will become the owners of the files. Usually, only the root user can change the owner of files on a system.
chr NUMBER
The chr function returns the character in the ASCII table associated with the number passed to the function. For example; chr(80); returns R. The pack function can be used to convert multiple characters at the same time.
chroot DIRNAME
The chroot function does the same thing as the chroot system call (see the chroot(2) man page for details). Basically, chroot tells the program that's currently running, as well as all exec calls and subprocesses, to use the directory named in DIRNAME as the new root directory. So, paths starting with / will begin in DIRNAME instead of the actual root directory of the file system. Only the root user can use the chroot function.
close FILEHANDLE
The close function is used to close a previously opened file handle (whether it is a file or a pipe). It performs the necessary system-level cleanup operations at the system level, and returns true if all those operations are successful. Note that all filehandles are closed automatically when a Perl program exits, so you can often get by with not explicitly closing all the filehandles that you open.
closedir DIRHANDLE
closedir closes a directory opened using the opendir function.
connect SOCKET, NAME
connect attempts to connect to a remote socket. NAME should contain the packed address appropriate to the type of socket. The function returns TRUE if it is successful or FALSE if it isn't. Identical to the connect system call.
cos EXPR
Returns the cosine of EXPR. To use the inverse cosine operation, you should use the POSIX::acos() function, or the Math::Trig module.
crypt PLAINTEXT, SALT
The crypt function is used to encrypt strings in the same way that passwords are stored in a Unix password file. The function accepts two arguments, the string to be encrypted, and the salt code used to seed the encryption algorithm. The crypt function is one-way; there is no known method for decrypting text enciphered using crypt (Unix tests passwords by using crypt on the password the user enters and testing the encrypted password against it).
dbmclose HASH
dbmclose breaks the binding between HASH and the DBM file with which it is associated. It has been superseded by the untie function.
dbmopen HASH, DBNAME, MODE
dbmopen binds a dbm, ndbm, sdbm, gdbm, or Berkeley DB file to hash. HASH is the name of the hash variable to which the database will be bound, and DBNAME is the name of the database file, minus the extension. If DBNAME doesn't exist, a new file will be created with permissions specified by MODE.
This function has been superseded by tie.
defined EXPR
defined is used to identify expressions that return the undefined value (as opposed to 0, newline, or other empty return values). It can be used to determine whether a subroutine exists or a scalar variable is defined. If no EXPR is given, defined checks to see if $_ is undefined.
delete EXPR
The delete function is used to remove elements from a hash. To delete a member of a hash, you simply pass the name of the hash and the key you want to remove to the delete function. Here's an example:
delete $hash{$key} ;
Note that because you're referring to a single member of the hash, you reference the hash variable in the scalar context (using $).
die LIST
die accepts a list as its argument. When die is called, the program exits returning the value of $!, and the list passed to die as an argument is printed to standard error. If the list does not end with a newline, the name of the program and the line number where execution halted are appended, along with a newline, to the output of the function.
Here's an example:
open (FILE, $file) or die "Can't open $file";
will return the following if $file can't be opened:
Can't open /tmp/file at test_program line 13.
do BLOCK do SUBROUTINE(LIST) do EXPR
When used with a block of code inside BLOCK, do executes the statements in a block and returns the value of the last statement in the block. If do is used with a loop expression, BLOCK is executed before the loop condition is tested for the first time.
do SUBROUTINE is a deprecated way to call a subroutine. do EXPR provides a way to run code in another file. EXPR is treated as the filename for a Perl file, and the code inside is executed. Even though you can use do in this way, you should probably use require or use instead because they are more robust.
dump LABEL
dump causes Perl to immediately dump core. You can then use the undump program to create a binary that will begin execution by issuing a goto LABEL command.
each HASH
The each function is used to grab values from a hash so that they can be iterated over in a loop. It acts differently depending on whether it is used in the scalar or the list context. Let's look at each.
In the scalar context, the each function returns the key for the next element in the hash. So, you could use it as follows:
while ($key = each %hash) { $hash{$key} ++; }
On the other hand, used in the list context, the each function returns a two-element list that contains the key and the value for the next element in the hash. Let's take a look:
while (($key, $value) = each %hash) { print "$key = $value "; }
eof FILEHANDLE eof () eof
The eof function returns 1 if the next read on FILEHANDLE will return the end of file marker, or if FILEHANDLE is not open. Used without an argument, eof evaluates the last file read. Called with empty parentheses, eof detects the end of the pseudo-file made up of all the files specified on the command line. As the perlfunc man page astutely points out, eof is rarely useful, because Perl returns the undefined value automatically when the end of a file is reached, making it easy to detect file endings without it.
eval EXPR eval BLOCK
eval is used to execute an expression or block of code as though it were a separate Perl program. It is executed within the context of the Perl program that's running, so when the expression within eval finishes executing, all the variables and other persistent values for the larger program are still defined.
The value returned by an eval is the value of the last expression evaluated. To explicitly return a particular value, you can use a return statement inside the eval. If a syntax or runtime error occurs within the eval statement, or a die statement is executed, the eval statement returns an undefined value, and the variable $@ contains the error message.
Because fatal errors executed within eval statements don't stop execution of the closing program, they can be used to trap errors, or run potentially volatile code.
exec LIST
The exec function executes a system command and never returns, unless the command does not exist. If LIST consists of more than one element, exec uses the system call execvp(3) with the arguments in LIST. If the argument contains a single scalar value, the argument is checked for shell metacharacters. If shell metacharacters exist, the argument is executed through /bin/sh -c, otherwise, the argument is broken into words and passed on to execvp.
exists EXPR
The exists function is used to check whether a particular key is defined within a hash. Whether a value is defined for that key is not checked by the exists function, it is strictly used to test keys. Here's an example of the usage:
if (exists $hash{$key} ) { print "Yes."; } else { print "No. "; }
exit EXPR
The exit function evaluates EXPR and immediately exits the program. The die function is usually a cleaner way to abort execution of a program, because the error information returned can be trapped.
exp EXPR
Returns e to the power of EXPR; if EXPR is omitted, then exp($) is assumed. For regular exponents, use the ** operator.
fcntl FILEHANDLE, FUNCTION, SCALAR
Used to emulate the fcntl(2) system call. You can use Fcntl; to obtain the function definitions needed to use this function. See the man page for more information on this function. fcntl returns a fatal error if it is not implemented on the platform on which it is called.
fileno FILEHANDLE
fileno returns a file descriptor for a given filehandle. A file descriptor is a small integer identifying the file. It can be used to construct bitmaps for use with select. If FILEHANDLE is not open, it returns undefined.
flock FILEHANDLE, OPERATION
This function calls the flock(2) system call on FILEHANDLE. For more information on the operations available, see the flock(2) man page. It produces a fatal error on systems that do not support flock(2) or some other file-locking mechanism.
fork
fork is used to fork a system call into a separate process. fork returns the child PID to the parent process. It is only implemented on Unix-like platforms. All the code inside the block will run in a new process.
format
The format function is designed to give Cobol programmers a head start in learning Perl. Actually, it provides a method for creating templates for formatted output. For all the details on generating output using format, read the perlform man page.
formline PICTURE, LIST
The formline function is used internally by formats. It is used to format LIST according to PICTURE. For more information, see the perlform man page.
getc FILEHANDLE
getc returns the next character from FILEHANDLE. If FILEHANDLE is omitted, getc returns the next character from STDIN. getc does not allow unbuffered input (in other words, if STDIN is the console, getc does not get the character until the buffer is flushed with a newline).
getlogin
Returns the current login from /etc/utmp, if any. If null, you should use getpwuid().
getpeername SOCKET
getpeername returns the packed sockaddr address of the other end of the SOCKET connection.
getpgrp PID
getpgrp returns the process group for the specified process. Supplying a PID of 0 will return the process group for the current process.
getppid
getppid returns the process ID for the parent process of the current process.
getpriority WHICH, WHO
getpriority returns the priority for a process, process group, or user, assuming the system function getpriority is implemented on this machine.
getsockname SOCKET
getsockname returns the packed sockaddr address of this end of the SOCKET connection.
getsockopt SOCKET, LEVEL, OPTNAME
getsockopt returns the requested option, or undefined in the case of an error.
glob EXPR
The glob function returns the value of EXPR with filename expansions, similar to those that would occur under a shell. If EXPR is omitted, $_ is assumed to be the argument.
gmtime EXPR
gmtime converts a time in the format returned by the time function (seconds since Jan. 1, 1970, 00:00), to Greenwich Standard Time (otherwise known as Greenwich Mean Time). The time is returned as a nine-element list. The contents of each element are provided in this example:
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time);
Note that all the items are returned in numerical format, and numbers in series (such as month and day of the week) begin with 0 rather than 1. This means that months range from 0 to 11. The year returned is the number of years since 1900, not simply the last two digits of the year, thus avoiding the dreaded year 2000 problem. If you use gmtime in the scalar context, it returns the time in ctime(3) format, like this:
Sat Jun 6 01:56:44 1998
goto LABEL goto EXPR goto &NAME
The goto function finds the statement labeled with LABEL, and continues executing from there. It cannot shift execution to statements within blocks that require initialization, such as subroutines or foreach loops. The other two usages of goto are rather arcane. goto EXPR is used to jump to a label that is specified by EXPR, which is scoped dynamically. goto &name substitutes a call to the named subroutine for the currently running subroutine, as though it was the one that was called in the first place.
grep EXPR, LIST grep BLOCK LIST
The grep function is used to search lists, and return all the elements in that list matching a particular pattern. grep accepts two arguments, an expression and a list. It returns another list containing each of the elements for which the expression was true. Let's look at an example:
@newarray = grep /red/, @oldarray;
@newarray will contain a list of all the items in @oldarray that contained the string red. If you call grep within the scalar context, it will return the number of items that matched, instead of a list of items that matched.
hex EXPR
hex reads EXPR as a hexadecimal string and returns the decimal value. If EXPR is omitted, the function reads $_.
import CLASSNAME LIST import CLASSNAME
import is not a built-in function; instead, it is implemented by modules that want to export names into another module. The import function is called by the use function when a module is loaded into a Perl program.
index STR, SUBSTR, POSITION index STR, SUBSTR
index is used to locate a substring within a larger string. It accepts three arguments, one of which is optional. The arguments are the string to search, the substring to search for, and the position where the search should begin (optional). index returns the position in the string where the first occurrence of the substring begins. For example, to find the string go within the larger string bingo, you could use the following code index ('bingo', 'go'),. To find the second occurrence of go within the string go or no go, you could use the optional third argument to start at position 3 in the string like this: index ('go or no go', 'go', 3);.
int EXPR
int returns the integer portion of a string. Basically, if a string begins with an integer, such as 55 MPH, int will return that integer, in this case, 55. Strings that don't begin with an integer will return 0 if you have Perl warnings turned on, you'll get a warning any non-numbers in the string.
ioctl FILEHANDLE, FUNCTION, SCALAR
ioctl is used to implement the ioctl(2) system call. You will probably need to use
require "ioctl.ph";
to import the function definitions for ioctl. If it doesn't exist, you will need to create your own function definitions based on the system's ioctl.h file.
join EXPR, LIST
The join function is the opposite of split, it is used to join the elements of a list into a single string. It takes two arguments, an expression and a list. The contents of the expression are used as the delimiter between the elements in the string that is returned.
keys HASH
The keys function returns an array containing all the keys in the named hash. It is oftentimes used to sort the keys in a hash before you iterate over them in a loop. Here's a common example:
foreach $key (sort (keys %hash)) { print $key, " = ", $value, " "; }
kill LIST
kill is actually used to send a signal to a list of processes, rather than simply killing them. The first argument in LIST must be the signal to send, the rest should be the processes that will receive the signal. To kill processes, you would use this code:
kill 1, 100, 102, 110;
To kill those same processes with extreme prejudice, you would use this code:
kill 9, 100, 102, 110;
You can supply the signal name inside quotes instead of the signal number if you prefer. See the signal(5) man page for more information on signals.
last LABEL last
The last command immediately exits the loop specified by LABEL. If no label is specified, the innermost loop exits.
lc EXPR
The lc function converts all the alphabetic characters in a string to lowercase. lc 'ABC'; returns abc. If no expression is provided, the lc function acts on $_.
lcfirst EXPR
Returns the value in EXPR with the first character lowercased. If EXPR is omitted, $_ is used.
length EXPR
length accepts a string as an argument, and returns an integer containing the length of the string in bytes. For example, length("dog"); returns 3. If EXPR is not supplied, $_ is used.
link OLDFILE, NEWFILE
Creates a hard (as opposed to symbolic) link from OLDFILE to NEWFILE. To create a symbolic link, use the symlink function.
listen SOCKET, QUEUESIZE
The listen function in Perl performs the same function as the listen system call. It returns TRUE if it succeeds, FALSE if it doesn't.
local EXPR
local specifies that the variables listed will be local to the currently executing block, loop, subroutine, eval {}, or do. If more than one variable is passed to local, they should be enclosed in parentheses. To restrict the scope of a variable, though, you should probably use my instead.
localtime EXPR
The localtime function is identical to gmtime, except that it returns the time converted to the local time zone instead of Greenwich time.
log EXPR
Returns the logarithm (base e) of EXPR, or $_ if EXPR is not provided.
lstat FILEHANDLE lstat EXPR lstat
lstat is identical to the stat function, except that it stats a symbolic link instead of the file the link points to. If EXPR is omitted, lstat acts on the value in $_.
map BLOCK LIST map EXPR, LIST
map provides an alternative to foreach for performing an operation on every element in a list. It can take two forms, and you can perform all the operations in a block of code on a list like this:
@backwards_words = map { lc; reverse; } @words;
The previous example reverses and lowercases each element in the array @words. The results of map are returned in a list context, which is why I assign them to an array. Note that when each element is processed, it is assigned to the $_ variable, which is why I can use the functions within the code block without arguments. To perform a single operation on each element of a list, map is called like this:
@newlist = map(uc, @oldlist);
Note that when a single operation is used with map, a comma is used to separate the function from the list that is being processed.
mkdir FILENAME, MODE
mkdir is used to create a new directory, the name of which is specified in FILENAME. You should set the permissions for the directory with MODE, which should be specified in standard octal format (as a bare number, not within quotation marks), and should include the SUID bit.
msgctl ID, CMD, ARG
msgctl calls the msgctl(2) system call. This function is available only on machines supporting System V IPC.
msgget KEY, FLAGS
Calls the System V IPC function msgget and returns the message queue ID, or undefined in the case of an error.
msgrcv ID, VAR, SIZE, TYPE, FLAGS
Calls the System V ICP function msgrcv to receive a message from message queue ID, into variable VAR, with a maximum size of SIZE. Returns TRUE if successful or FALSE if there's an error.
msgsnd ID, MSG, FLAGS
Calls the System V IPC function msgsnd to send MSG to the message queue specified in ID. Returns TRUE if successful or FALSE if there's an error.
my EXPR
my is used to scope the listed variables so that they are local to the current block, eval {}, subroutine, or imported file. If more than one variable is supplied, they must be placed within parentheses.
next LABEL next
When the next command is encountered within a loop, it skips immediately to the next iteration of that loop.
no MODULE LIST
The no module is the opposite of the use operator. You can find more information in the perlobj man page.
oct EXPR
oct reads EXPR as an octal string and returns the decimal value, unless the string starts with 0x, in which case it is interpreted as a hex value. If EXPR is omitted, the function reads $_.
open FILEHANDLE, EXPR
The open function opens the file specified in EXPR, and assigns it to FILEHANDLE. If EXPR is omitted, a variable with the same name as FILEHANDLE is assumed to contain the name of the file.
By prepending < to the filename you can open it for input. By prepending > to the filename you can open it for output. To append data to the output file, instead of overwriting it, you should prepend the filename with >>. To open a filehandle using a pipe instead of standard input and output, you can use the pipe character. Placing a | before the program name opens a pipe to that program, whereas placing a | after the filename opens a pipe from the program to your filehandle.
For more information on the open function, look at Chapter 15, “Working with Files and I/O.”
opendir DIRHANDLE, EXPR
The opendir function opens the directory specified in EXPR for input, and assigns it to DIRHANDLE. A list of entries in the directory can then be read from the directory handle. Note that the namespace for directory handles does not overlap with that for filehandles.
ord EXPR
Returns the numeric ASCII value of the first character of EXPR. If EXPR is omitted, $_ is used.
pack TEMPLATE, LIST
pack accepts a list of values, packs it into a binary structure, and returns the string containing that structure. The TEMPLATE is a list of characters that gives the order and type of the values.
Each letter can be followed with a number, which is used as the repeat count for that letter. The unpack function can be used to extract items stored in a binary structure.
package NAMESPACE
The package function declares that all the variables inside the innermost enclosing block, subroutine, eval, or file, belong to NAMESPACE. For more information, see the permod man page.
pipe READHANDLE, WRITEHANDLE
pipe opens a pipe from READHANDLE to WRITEHANDLE, similar to the system call of the same name.
pop ARRAY
The pop function removes the last item in an array (shortening it by one element) and returns it as a scalar value. Both push (which will be discussed later) and pop are known as stack functions. If you imagine an array as a stack of trays in a cafeteria, pop is used to remove the top item from that stack.
pos SCALAR
Returns the location in SCALAR where the last m//g search left off. If SCALAR is not specified, $_ is used.
print FILEHANDLE LIST print LIST print
The print function is used to output the data passed to it in the list context to standard output, or if a filehandle is specified, to that filehandle. If the list of data to print is omitted, the contents of $_ are printed by default. Note that there shouldn't be a comma between the filehandle and the actual list of data being printed, so to print some data to the filehandle FILE, you would use the following:
print FILE $data;
Or, to print a list of data, you could do this:
print FILE $data, ' ', $more_data, ' ';
printf FILEHANDLE LIST printf LIST
printf is used to format output using the conventions set for the sprintf function. Basically, this:
printf FILEHANDLE FORMAT, LIST;
is identical to:
print FILEHANDLE sprintf(FORMAT, LIST);
push ARRAY, LIST
push is used to add an element onto the end of an array. When you push a scalar value onto an array, the array is lengthened by one element, and that value is assigned to the last element in the array. Imagining the same stack of trays from the description of the pop function, you can envision the push function as putting a tray onto the top of the stack. You can also push multiple values onto the array by using a list as the argument to the push function.
quotemeta EXPR quotemeta
quotemeta returns the value of EXPR, with all the nonalphanumeric characters escaped using backslashes. Uses $_ when EXPR is omitted.
rand EXPR rand
The rand function returns a random number between 0 and EXPR. If EXPR is omitted, the function returns a value between 0 and 1 (not including 1). See srand for information on seeding the random number generator.
read FILEHANDLE, SCALAR, LENGTH, OFFSET read FILEHANDLE, SCALAR, LENGTH
The read function is used to read an arbitrary number of bytes of data from a filehandle into a scalar value. It accepts four arguments; filehandle, scalar, length, and offset (offset is optional). The filehandle argument specifies the filehandle from which to read the data. The scalar argument defines the variable to which the data will be assigned. Length specifies how many bytes of data will be read. Offset is used if you want to read the data from a place other than the beginning of the string. Here's an example, which would read 1024 bytes of data from 2048 bytes into the filehandle FILE, and assign them to the variable $chunk:
read FILE, $chunk, 1024, 2048;
readdir DIRHANDLE
readdir is used to read entries from a directory that has been opened using the opendir function. When used in the scalar context, it returns the next entry in the directory. In the list context, it returns all the remaining entries in the directory. If all the entries in the directory have already been read, it returns the undefined value.
readlink EXPR
The readlink function reads the value of a symbolic link. If symbolic links are not im plemented on the platform, it returns a fatal error. If EXPR is omitted, the value in $_ is used.
recv SOCKET, SCALAR, LEN, FLAGS
recv is used to receive a message on a socket, using a C recvfrom. Receives LEN bytes into variable SCALAR from SOCKET. It returns the address of the sender, unless there's an error, in which case it returns undefined. recv accepts the same flags as the system call of the same name.
redo LABEL redo
redo restarts the current loop block, without reevaluating the loop's test condition. If LABEL is omitted, redo acts on the innermost enclosing block.
ref EXPR
ref returns TRUE if EXPR is a reference, FALSE otherwise. If EXPR is omitted, $_ is used.
rename OLDNAME, NEWNAME
The rename function changes the name of the file OLDNAME to NEWNAME.
require EXPR
require is most often used to load an external Perl file into the current program, but more generally speaking, it is used to base some sort of dependency on its argument. If EXPR is numeric, that version of Perl is required for the program to run. If no argument is supplied, $_ is used.
To load a file, you should provide the filename as the argument to require. If you provide the filename as a bare word, .pm is automatically appended, and :: will be replaced by / to make it easy to load standard modules. The required file must end with a statement that evaluates as true. Customarily, files built to be required end with the 1; statement.
reset EXPR reset
reset is used to clear global variables or ?? searches, and is often used at the beginning of a loop, or in the continue block at the end of a loop. reset clears the values of all the variables beginning with the character provided in EXPR. If called with no arguments, reset clears all ?? searches.
return EXPR
The return function suspends execution of an eval, subroutine, or do FILE, and returns the value of EXPR. If no return statement is provided, the value of the last expression evaluated will be returned.
reverse LIST
The reverse function accepts a scalar value or a list as its argument. For scalar values, it reverses of the order of the characters in the scalar. For example, reverse "red"; returns der. When a list is passed to reverse, the order of the items in the list is reversed. reverse ("red", "green", "blue"); returns ("blue", "green", "red").
rewinddir DIRHANDLE
rewinddir resets the directory handle for a directory opened with readdir back to the first entry in that directory.
rmdir FILENAME
rmdir removes the directory specified by FILENAME, if it is empty. If the directory is not empty, or the function fails for some other reason, it returns 1. It returns 0 if it is successful. If FILENAME is not provided, the value in $_ is used.
scalar EXPR
Forces the value of EXPR to be evaluated in the scalar context, and returns the value of EXPR.
seek FILEHANDLE, OFFSET, WHENCE
seek is used to set the position of FILEHANDLE. WHENCE can be any of the following values; 0 to set the position to POSITION, 1 to add POSITION to the current position, and 2 to set it to EOF plus POSITION (usually a negative number is used here, for obvious reasons).
seekdir DIRHANDLE, POS
seekdir sets the position of DIRHANDLE for the readdir function. POS must be a value returned by telldir.
select FILEHANDLE select
Called without arguments, select returns the currently selected filehandle. When you provide a filehandle (or an expression that returns a filehandle) to select, that filehandle is now the default handle to which output will be sent, in other words, it becomes standard output. So, if you will be printing a number of items to a particular filehandle, it might be easier to select that filehandle, and leave the filehandles out of your print statements.
semctl ID, SEMNUM, CMD, ARG
semctl calls the System V IPC system call semctl(2).
semget KEY, NSEMS, SIZE, FLAGS
semget calls the System V IPC system call semget(2), and returns the semaphore ID, or undefined if there is an error.
semop KEY, OPSTRING
Calls the System V IPC system call semop(2), which performs semaphore operations like signaling and waiting.
send SOCKET, MSG, FLAGS, TO send SOCKET, MSG, FLAGS
The send function sends a message over a socket. If the socket is not connected, you must specify an address to send to. The function takes the same flags as the send system call, and returns the number of characters sent if it is successful, or undefined if it fails.
setpgrp PID, PGRP
setpgrp sets the process group for the specified PID. If 0 is supplied as the PID, the process group is set for the current process. Produces a fatal error if setpgrp(2) is not supported by the system.
setpriority WHICH, WHO, PRIORITY
Sets the priority for a process, process group, or user. If setpriority(2) is not supported, a fatal error occurs.
setsockopt SOCKET, LEVEL, OPTNAME, OPTVAL
setsockopt is used to set the specified option for a socket. If there is an error, undefined is returned. Use undef for OPTVAL to set an option without specifying a value for the option.
shift ARRAY shift
The shift function is the opposite of the unshift function, it removes the first element from an array and returns it as a scalar value. The indexes of all the other elements in the array are decreased by one, and the array winds up one element shorter than it was before. shift is commonly used to process arguments passed to a user-written function. As you know, arguments are passed to functions through the array @_. By using commands such as $arg = shift @_;, you can easily make use of function arguments without worrying about their indexes.
shmctl ID, CMD, ARG
shmctl calls the System V shmctl(2) system call. For more information on all the shared memory functions (which begin with shm), see the perlipc man page.
shmget KEY, SIZE, FLAGS
shmget calls the System V shmget(2) system call.
shmread ID, VAR, POS, SIZE
shmread calls the System V shmread(2) system call.
shmwrite ID, STRING, POS, SIZE
shmwrite calls the System V shmwrite(2) system call.
shutdown SOCKET, HOW
shutdown closes a socket connection in the manner specified with HOW, which uses the same syntax as the shutdown system call.
sin EXPR
Returns the sine of EXPR, or of $_ if no argument is provided.
sleep EXPR sleep
sleep causes the program to sleep for EXPR seconds, or if EXPR is not specified, to sleep indefinitely. sleep can be interrupted using the SIGALRM signal. It returns the number of seconds actually slept.
socket SOCKET, DOMAIN, TYPE, PROTOCOL
The socket function is used to open a socket attached to filehandle SOCKET. DOMAIN, TYPE, and PROTOCOL are specified in the same way that they are specified for the socket system call. You should use Socket; to import the Socket module before you call the socket function to import the proper definitions.
socketpair SOCKET1, SOCKET2, DOMAIN, TYPE, PAIR
The socketpair function creates a pair of unnamed sockets, in the specified domain, of the specified type. A fatal error occurs if this function is unimplemented, if it is successful, it returns TRUE.
sort SUBNAME LIST sort BLOCK LIST sort LIST
The sort routine is used to sort the entries in a list, and returns the members in the list in the sorted order. There are three ways sort can be used; the simplest is to simply invoke sort with the list you want to sort as the argument. This returns the list sorted in standard string comparison order.
Another option is to supply a subroutine to compare with the items in the list. The subroutine should return an integer less than, equal to, or greater than zero, depending on how the elements of the list should be ordered (the <=> operator, which performs numeric comparisons, and the cmp operator, which provides string comparisons are often used in these subroutines).
Although the subroutine method described in the preceding paragraph can be used to sort lists by criteria other than the default, it is more common to simply insert a block of code as the first argument to the function call. You've probably seen the sort function used like this:
@sortedlist = sort { $a <=> $b } @list;
The preceding example sorts @list in ascending numerical order and assigns the list returned to the array @sortedlist. The items being compared by the sort routine are sent to the code block (or subroutine) as $a and $b, so the preceding block of code compares the two items using the <=> operator. Let's take a look at some other common code blocks used with the sort function:
# Sort in lexical order (the same as the default sort) @sortedlist = sort {$a cmp $b } @list; # Sort in descending lexical order @sortedlist = sort { $b cmp $a } @list; # Sort in numerical order @sortedlist = sort { $a <=> $b } @list; # Sort in descending numerical order @sortedlist = sort { $b <=> $a } @list;
splice ARRAY, OFFSET, LENGTH, LIST splice ARRAY, OFFSET, LENGTH splice ARRAY, OFFSET
splice is the Swiss Army Knife of array functions; it provides a general purpose for inserting elements into an array, removing elements from an array, or replacing elements in an array with new values. splice can be called with up to four arguments, the last two of which are optional. The first argument should be the array you want to splice. The second argument is the offset, the position in the array where the action will take place (to count back from the end of the array, you can use a negative number). The third argument, which is optional, is the number of items you want to remove (if you leave it out, all the items from the offset to the end of the array will be removed). The rest of the arguments are assumed to be a list of items that will be inserted at the offset. That sounds pretty confusing, but an example will make it all clear.
To delete all the elements in the array after the second element (remember that array indexes begin with 0), you could use the following code:
splice(@array, 2);
To insert a new scalar value between the second and third elements in an array, without removing anything, you would use
splice(@array, 2, 0, "new value");
To replace the second and third elements in an array with three new elements, you could use the following:
splice(@array, 2, 2, "red", "green", "blue");
You should note that after an array is spliced, all the elements in the array are reindexed to reflect the changes in the structure. So, in the previous example, all the indexes for the items after the ones we inserted would be incremented by one because we replaced two items with three.
split /PATTERN/, EXPR, LIMIT split /PATTERN/, EXPR split /PATTERN/ split
The split function is used to break a string into multiple parts and return those parts as a list. It accepts up to three arguments: a pattern on which to split, the string to split up, and a limit on the number of list items returned (optional). If you leave out the string to be split up, the value stored in $_ will be used. You can also leave out the pattern on which to split up the string, and Perl will use whitespace as the delimiter. The pattern argument is always a regular expression contained within //, so to split the string on commas, you would use /,/ as the pattern. Let's look at some examples:
# Empty pattern splits string into individual characters @letters = split //, "word"; # A space in the pattern splits the sentence # into individual words @words = split / /, "this is a sentence"; # This pattern splits on any white space instead of just # spaces (same as the default) @words = split /s/, "this is a sentence"; # The third argument ensures that only the first two items # extracted from the string will be returned in the list. ($first, $second) = split /s/, "this is a sentence", 2;
sprintf FORMAT, LIST
The Perl sprintf function is used to format strings using the conventions established for the C sprintf function. Here's a table listing the conversions used with sprintf:
For detailed information on the conventions used with sprintf, check out the man page for printf(3).
sqrt EXPR
sqrt returns the square root of EXPR, or of $_ if EXPR is not supplied.
srand EXPR
srand seeds Perl's random number generator. If you leave off EXPR, srand(time) is assumed. You should only use it once in your program.
stat FILEHANDLE
The stat function gathers some information on the file specified by FILEHANDLE, and returns a list containing that information. It can also accept an expression containing a filename instead of an open filehandle. If no argument is provided, the stat function uses the value of $_ as its argument. The data returned by stat is in list form, and includes
The device number of the filesystem
The file's inode
The file mode (type and permissions)
The number of hard links to the file
The uid and gid of the file's owner
The device identifier (for special files)
The size of the file in bytes
The times since the file was last accessed, last modified, and the inode was changed
The file's block size
The number of blocks used
Let's take a look at the values returned by stat. This is how you might assign the list returned by stat to a group of variables.
study SCALAR study
study takes extra time to study SCALAR (or $_ if SCALAR is omitted), to make future pattern matches on the value more efficient. Whether this saves time or not depends on how many pattern matches you plan on making, and the nature of those matches.
substr EXPR, OFFSET, LENGTH, REPLACEMENT substr EXPR, OFFSET, LENGTH substr EXPR, OFFSET
substr is used to extract some characters from a string. It accepts three arguments, the last of which is optional. The arguments are the expression from which characters should be extracted (this can be a scalar value, a variable, or a call to another function), the position to begin extracting characters, and, optionally, the number of characters to extract. So, substr("foobar", 3, 2); returns ba. Leaving out the length, like this: substr("foobar", 3); returns bar. You can also use a negative offset value, which will count positions from the end of the string instead of the beginning. Here's an example: substr("foobar", -4, 2); returns ob.
symlink OLDFILE, NEWFILE
The symlink function is used to create a symbolic link from OLDFILE to NEWFILE. symlink produces a fatal error if the system doesn't support symbolic links.
syscall LIST
syscall calls the system call specified as the first argument in LIST. The remaining items in LIST are passed to the system call as arguments.
sysopen FILEHANDLE, FILENAME, MODE sysopen FILEHANDLE, FILENAME, MODE, PERMS
Opens the file specified by FILENAME, associating it with FILEHANDLE. If the file does not exist, it is created.
sysread FILEHANDLE, SCALAR, LENGTH, OFFSET sysread FILEHANDLE, SCALAR, LENGTH
Reads LENGTH bytes from FILEHANDLE into SCALAR using the read(2) system call. Returns the number of bytes read, or undefined if there is an error. OFFSET places the bytes read that many bytes into the string, rather than at the beginning.
sysseek FILEHANDLE, POSITION, WHENCE
Similar to the seek function, except that it uses the lseek(2) system call rather than the fseek(2) call.
system LIST
The system function works exactly like exec LIST, except that it forks a new process and executes the commands in LIST in that process, and then returns.
syswrite FILEHANDLE, SCALAR, LENGTH, OFFSET syswrite FILEHANDLE, SCALAR, LENGTH
syswrite attempts to write LENGTH bytes of data from variable SCALAR to FILEHANDLE, using the write(2) system call. It returns the number of bytes written, or undefined in the case of an error.
tell FILEHANDLE
tell returns the current position for the specified filehandle, or if no filehandle is specified, for the last file read.
telldir DIRHANDLE
telldir returns the current position in the specified directory handle.
tie VARIABLE, CLASSNAME, LIST
tie binds a variable to a package class that will provide the implementation for a variable. VARIABLE is the name of the variable to be bound, and CLASSNAME is the name of the class implementing objects of the correct type. Any additional arguments are passed to the new method of the class.
tied VARIABLE
tied returns a reference to the underlying object of VARIABLE, if it is tied to a package. If the variable isn't tied, it returns undefined.
time
The time function returns the number of seconds that have elapsed since the time that the system considers the epoch. On most systems, this is 00:00:00 UTC, January 1, 1970; on the MacOs, 00:00:00, January 1, 1904. Most often passed to localtime or gmtime for formatting.
times
times returns a four element array containing the user and system times for the current process, and its children. Here's an example:
($user, $system, $cuser, $csystem) = times;
truncate FILEHANDLE, LENGTH truncate EXPR, LENGTH
Truncates the file assigned to FILEHANDLE, or specified by EXPR, to LENGTH. If truncate isn't implemented on the system, a fatal error occurs.
uc EXPR
Just as lc converts all the letters in a string to lowercase, uc converts all the letters in a string to uppercase.
ucfirst EXPR
Returns EXPR with the first character capitalized.
umask EXPR
umask is used to set the default umask for the process. It accepts an octal number (not a string of digits). The umask function is useful if your program will be creating a number of files. If EXPR is omitted, umask returns the current umask.
undef EXPR
undef is used to eliminate the value of a variable. It can be used on a scalar variable, an entire array, or an entire hash.
unlink (LIST)
unlink deletes the files passed to it via LIST. It returns the number of files it successfully deletes. If no list is passed to unlink, it uses $_ as its argument.
unpack TEMPLATE, EXPR
unpack is the reverse of pack. It accepts a data structure and translates it into a list, based on TEMPLATE. The TEMPLATE format is the same as that for pack.
unshift ARRAY, LIST
The unshift function inserts a scalar value as the first element in an array, moving the indexes of all the other items in the array up by one.
utime LIST
utime is the Perl equivalent of the Unix touch command; it sets the access and modification times for a list of files. The first two arguments must contain the numerical access and modification times for the files. All the arguments after the first two are assumed to be files that should have their access and modification dates changed. The function returns the number of files that were successfully touched.
values HASH
Returns an array containing the values for each of the items in a hash, much like keys returns an array of the keys in a hash.
vec EXPR, OFFSET, BITS
vec treats a string (specified by EXPR) as a vector of unsigned integers, and returns the value of the bit field specified by OFFSET.
wait
wait simply waits for a child process to die, and then returns the PID of that process.
waitpid PID, FLAGS
The waitpid function waits for a particular child process (specified by PID) to exit, and then returns the process ID of the dead process.
wantarray
wantarray returns TRUE if the context of the subroutine currently being executed requires a list value. If it was called in the scalar or void context, this function returns FALSE. To avoid executing the entire subroutine, you can use a statement like this to make sure that the subroutine was called in the list context:
return unless defined wantarray;
warn LIST
warn is used to print a message to standard error without terminating the program. Other than the fact that the program doesn't stop executing, it is just like the die function.
write FILEHANDLE
The write function is used to output data using a template defined with the format function. For more information, check out the perlform man page.