![]()
|
Functions
Perl has a large number of functions that come as standard with most implementations, and an even wider range of additional modules, each with its own additional functions. This chapter lists all the standard functions alphabetically for reference. Each function is assigned a category. There are two main categories; list operators, which can take more than one argument, and named unary operators, which can only take one argument. A secondary category is noted in parentheses so you can see, at a glance, the type of operation the function performs. This is a very rough categorization, as many functions might overlap in any category scheme. For each function the form of the arguments is listed. If there are multiple forms of calling the function, there will be multiple lines describing each form. The meanings of the arguments are described in the text. The type of value returned by the function is listed. This is usually specified in more detail in the function description. Two categories of functions, those dealing with sockets and those dealing with System V interprocess communications, are not dealt with in great detail. Both of these categories of function are direct counterparts of UNIX system functions. The chapter includes
-ACompliance
SyntaxCategory named unary operator (file test) Arguments handle Arguments filename Arguments none Return Value integer (age of file in days since last access relative to $BASETIME) DefinitionThe file test operator takes one file handle or filename as an argument. It returns age of file in days since last access relative to $BASETIME. All file test operators can take a special argument underscore, which means that the test is carried out on the same file handle as the last file test, stat(), or lstat() call. If no argument is supplied, $_ is used. Exampleprint "-A ", -A "/etc/fstab", "\n"; -BCompliance
SyntaxCategory named unary operator (file test) Arguments handle Arguments filename Arguments none Return Value 1 (true) '' (false) Definition1The file test operator takes one file handle or filename as an argument. It returns 1 (true) if the file is binary. It returns '' (false) if the file is not binary. The first characters of the file are checked to see if the high bit is set and if a suitable number do have the high bit set the file is assumed to be binary. If the file is empty it is returned as binary. Because this test involves reading the file itself, it is best to test to learn if the file exists as a plain file (-f), first. All file test operators can take a special argument underscore, which means that the test is carried out on the same file handle as the last file test, stat(), or lstat() call. If no argument is supplied, $_ is used. Example(-B "/etc/fstab") ? print("-B fstab is binary\n") : print("-B fstab is not binary\n"); -bCompliance
SyntaxCategory named unary operator (file test) Arguments handle Arguments filename Arguments none Return Value 1 (true) '' (false) DefinitionThe file test operator takes one file handle or filename as an argument. It returns 1 (true) if the file is a block special file (that is, a UNIX /dev device file). It returns '' (false) if the file is not a block special file. All file test operators can take a special argument underscore, which means that the test is carried out on the same file handle as the last file test, stat(), or lstat() call. If no argument is supplied, $_ is used. Example(-b "/dev/hda1") ? print("-b hda1 is block\n") : print("-b hda1 is not block\n"); -CCompliance
SyntaxCategory named unary operator (file test) Arguments handle Arguments filename Arguments none Return Value integer (age of file in days since last inode change relative to $BASETIME) DefinitionThe file test operator takes one file handle or filename as an argument. It returns age of file in days since last inode change relative to $BASETIME. All file test operators can take a special argument underscore, which means that the test is carried out on the same file handle as the last file test, stat(), or lstat() call. If no argument is supplied, $_ is used. Exampleprint "-C ", -C "/etc/fstab", "\n"; -cCompliance
SyntaxCategory named unary operator (file test) Arguments handle Arguments filename Arguments none Return Value 1 (true) '' (false) DefinitionThe file test operator takes one file handle or filename as an argument. It returns 1 (true) if the file is a character special file. It returns '' (false) if the file is not a character special file. All file test operators can take a special argument underscore, which means that the test is carried out on the same file handle as the last file test, stat(), or lstat() call. If no argument is supplied, $_ is used. Example(-c "/dev/tty0") ? print("-c tty0 is char\n") : print("-c tty0 is not char\n"); -dCompliance
SyntaxCategory named unary operator (file test) Arguments handle Arguments filename Arguments none Return Value 1 (true) '' (false) DefinitionThe file test operator takes one file handle or filename as an argument. It returns 1 (true) if the file is a directory. It returns '' (false) if the file is not a directory. All file test operators can take a special argument underscore, which means that the test is carried out on the same file handle as the last file test, stat(), or lstat() call. If no argument is supplied, $_ is used. Example(-d "/") ? print("-d / is dir\n") : print("-d / is not dir\n"); -eCompliance
SyntaxCategory named unary operator (file test) Arguments handle Arguments filename Arguments none Return Value 1 (true) '' (false) DefinitionThe file test operator takes one file handle or filename as an argument. It returns 1 (true) if file exists. It returns '' (false) if the file does not exist. All file test operators can take a special argument underscore, which means that the test is carried out on the same file handle as the last file test, stat(), or lstat() call. If no argument is supplied, $_ is used. Example(-e "/") ? print("-e / exists\n") : print("-e / exists\n"); -fCompliance
SyntaxCategory named unary operator (file test) Arguments handle Arguments filename Arguments none Return Value 1 (true) '' (false) DefinitionThe file test operator takes one file handle or filename as an argument. It returns 1 (true) if the file is a plain file. It returns '' (false) if the file is not a plain file. A plain file is any file that is not a special block device (-b), a special character device (-c), a directory (-d), a symbolic link (-l), a pipe (-p), a named socket (-S), or a direct link to an I/O terminal (-t). All file test operators can take a special argument underscore, which means that the test is carried out on the same file handle as the last file test, stat(), or lstat() call. If no argument is supplied, $_ is used. Example(-f "/") ? print("-f / is plain\n") : print("-f / is not plain\n"); -gCompliance
SyntaxCategory named unary operator (file test) Arguments handle Arguments filename Arguments none Return Value 1 (true) '' (false) DefinitionThe file test operator takes one file handle or filename as an argument. It returns 1 (true) if the file has the setgid bit set. It returns '' (false) if the file does not have the setgid bit set. In UNIX, setgid allows an executable to run as if it was being run by the group, which owns the executable itself while executing (for example, if a binary is owned by the group wwwstat, and the binary has the getgid bit set, then that binary has access to all files that the wwwstat group can access while the binary is running, even when the binary is run by someone who is not actually a member of the wwwstat group). All file test operators can take a special argument underscore, which means that the test is carried out on the same file handle as the last file test, stat(), or lstat() call. If no argument is supplied, $_ is used. Example(-g "/vmlinuz") ? print("-g /vmlinuz has setgid\n") : print("-g /vmlinuz has not setgid\n"); -kCompliance
SyntaxCategory named unary operator (file test) Arguments handle Arguments filename Arguments none Return Value 1 (true) '' (false) DefinitionThe file test operator takes one file handle or filename as an argument. It returns 1 (true) if the sticky bit is set. It returns '' (false) if the sticky bit is not set. In UNIX, the sticky bit can mark an executable file to be held in memory when exited (for example, if the binary ls is marked as sticky, when the first person runs it, it is loaded from disk to memory and executed, but when the execution finishes, the binary stays in memory so that when the next person runs ls it does not need to be loaded into memory again because it is already there). This is normally set for frequently used commands to optimize execution speed. All file test operators can take a special argument underscore, which means that the test is carried out on the same file handle as the last file test, stat(), or lstat() call. If no argument is supplied, $_ is used. Example(-k "/vmlinuz") ? print("-k /vmlinuz is sticky\n") : print("-k /vmlinuz is not sticky\n"); -lCompliance
SyntaxCategory named unary operator (file test) Arguments handle Arguments filename Arguments none Return Value 1 (true) '' (false) DefinitionThe file test operator takes one file handle or filename as an argument. It returns 1 (true) if the file is a symbolic link. It returns '' (false) if the file is not a symbolic link. All file test operators can take a special argument underscore, which means that the test is carried out on the same file handle as the last file test, stat(), or lstat() call. If no argument is supplied, $_ is used. Example(-l "/vmlinuz") ? print("-l /vmlinuz is symlink\n") : print("-l /vmlinuz is not symlink\n"); -MCompliance
SyntaxCategory named unary operator (file test) Arguments handle Arguments filename Arguments none Return Value integer (age of file in days relative to $BASETIME) DefinitionThe file test operator takes one file handle or filename as an argument. It returns the age of the file in days relative to $BASETIME. All file test operators can take a special argument underscore, which means that the test is carried out on the same file handle as the last file test, stat(), or lstat() call. If no argument is supplied, $_ is used. Exampleprint "-M ", -M "/etc/fstab", "\n"; -OCompliance
SyntaxCategory named unary operator (file test) Arguments handle Arguments filename Arguments none Return Value 1 (true) '' (false) DefinitionThe file test operator takes one file handle or filename as an argument. It returns 1 (true) if the file is owned by the real UID/GID and it returns '' (false) otherwise. For the superuser it always returns true. All file test operators can take a special argument underscore, which means that the test is carried out on the same file handle as the last file test, stat(), or lstat() call. If no argument is supplied, $_ is used. Example(-o "/vmlinuz") ? print("-o /vmlinuz is owned by real uid/gid\n") : print("-o /vmlinuz is not owned by real uid/ gid\n"); -oCompliance
SyntaxCategory named unary operator (file test) Arguments handle Arguments filename Arguments none Return Value 1 (true) '' (false) DefinitionThe file test operator takes one file handle or filename as an argument. This function returns 1 (true) if the file is owned by the effective UID/GID and it returns '' (false) otherwise. For the superuser it always returns true. All file test operators can take a special argument underscore, which means that the test is carried out on the same file handle as the last file test, stat(), or lstat() call. If no argument is supplied, $_ is used. Example(-O "/vmlinuz") ? print("-O /vmlinuz is owned by effective uid/gid\n") : print("-o /vmlinuz is not owned by effective uid/gid\n"); -pCompliance
SyntaxCategory named unary operator (file test) Arguments handle Arguments filename Arguments none Return Value 1 (true) '' (false) DefinitionThe file test operator takes one file handle or filename as an argument. It returns 1 (true) if the file is a named pipe. It returns '' (false) if the file is not a named pipe. All file test operators can take a special argument underscore, which means that the test is carried out on the same file handle as the last file test, stat(), or lstat() call. If no argument is supplied, $_ is used. Example(-p "/vmlinuz") ? print("-p /vmlinuz is named pipe\n") : print("-p /vmlinuz is not named pipe\n"); -RCompliance15
SyntaxCategory named unary operator (file test) Arguments handle Arguments filename Arguments none Return Value 1 (true) '' (false) DefinitionThe file test operator takes one file handle or filename as an argument. It returns 1 (true) if the file is readable by the effective UID/GID and it returns '' (false) otherwise. For the superuser it always returns true. All file test operators can take a special argument underscore, which means that the test is carried out on the same file handle as the last file test, stat(), or lstat() call. If no argument is supplied, $_ is used. Example(-R "/vmlinuz") ? print("-R /vmlinuz is readable by effective uid/gid\n") : print("-R /vmlinuz is not readable by effective uid/gid\n"); -rCompliance
SyntaxCategory named unary operator (file test) Arguments handle Arguments filename Arguments none Return Value 1 (true) '' (false) DefinitionThe file test operator takes one file handle or filename as an argument. It returns 1 (true) if the file is readable by the real UID/GID and it returns '' (false) otherwise. For the superuser it always returns true. All file test operators can take a special argument underscore, which means that the test is carried out on the same file handle as the last file test, stat(), or lstat() call. If no argument is supplied, $_ is used. Example(-r "/vmlinuz") ? print("-r /vmlinuz is readable by real uid/gid\n") : print("-r /vmlinuz is not readable by real uid/ gid\n"); -SCompliance
SyntaxCategory named unary operator (file test) Arguments handle Arguments filename Arguments none Return Value 1 (true) '' (false) DefinitionThe file test operator takes one file handle or filename as an argument. It returns 1 (true) if the file is a symbolic link. It returns '' (false) if the file is not a symbolic link. All file test operators can take a special argument underscore, which means that the test is carried out on the same file handle as the last file test, stat(), or lstat() call. If no argument is supplied, $_ is used. Example(-S "/vmlinuz") ? print("-S /vmlinuz is socket\n") : print("-S /vmlinuz is not socket\n"); -sCompliance
SyntaxCategory named unary operator (file test) Arguments handle Arguments filename Arguments none Return Value integer (size) '' (false) DefinitionThe file test operator takes one file handle or filename as an argument. It returns size in bytes as an integer if the file has a non-zero size. It returns '' (false) if the file has zero size. All file test operators can take a special argument underscore, which means that the test is carried out on the same file handle as the last file test, stat(), or lstat() call. If no argument is supplied, $_ is used. Example(-s "/vmlinuz") ? print("-s /vmlinuz has non-zero size\n") : print("-s /vmlinuz does not have non-zero size\n"); -TCompliance
SyntaxCategory named unary operator (file test) Arguments handle Arguments filename Arguments none Return Value 1 (true) '' (false) DefinitionThe file test operator takes one file handle or filename as an argument. It returns 1 (true) if the file is a text file. It returns '' (false) if the file is not a text file. The first characters of the file are checked to see if the high bit is set, and if a suitable number are not set the file is assumed to be text. If the file is empty, true is returned. Because this test involves reading the file itself, it is best to test to learn if the file exists as a plain file (-f) first. All file test operators can take a special argument underscore, which means that the test is carried out on the same file handle as the last file test, stat(), or lstat() call. If no argument is supplied, $_ is used. Example(-T "/vmlinuz") ? print("-T /vmlinuz is text file\n") : print("-T /vmlinuz is not text file\n"); -tCompliance
SyntaxCategory named unary operator (file test) Arguments handle Arguments filename Arguments none Return Value 1 (true) '' (false) DefinitionThe file test operator takes one file handle or filename as an argument. It returns 1 (true) if the file is a terminal tty device. It returns '' (false) if the file is not. All file test operators can take a special argument underscore, which means that the test is carried out on the same file handle as the last file test, stat(), or lstat() call. If no argument is supplied, STDIN is used. Example(-t "/vmlinuz") ? print("-t /vmlinuz is tty\n") : print("-t /vmlinuz is not tty\n"); -uCompliance
SyntaxCategory named unary operator (file test) Arguments handle Arguments filename Arguments none Return Value 1 (true) '' (false) DefinitionThe file test operator takes one file handle or filename as an argument. It returns 1 (true) if the file has the setuid bit set. It returns '' (false) if the files does not have the setuid bit set. In UNIX, setuid allows an executable to take on the UID of the user ownership of the executable itself while executing. All file test operators can take a special argument underscore, which means that the test is carried out on the same file handle as the last file test, stat(), or lstat() call. If no argument is supplied, $_ is used. Example(-u "/vmlinuz") ? print("-u /vmlinuz has suid set\n") : print("-u /vmlinuz does not have suid set\n"); -WCompliance
SyntaxCategory named unary operator (file test) Arguments handle Arguments filename Arguments none Return Value 1 (true) '' (false) DefinitionThe file test operator takes one file handle or filename as an argument. It returns 1 (true) if the file is writable by the real UID/GID.It returns '' (false) otherwise. For the superuser it always returns true. All file test operators can take a special argument underscore, which means that the test is carried out on the same file handle as the last file test, stat(), or lstat() call. If no argument is supplied, $_ is used. Example(-W "/vmlinuz") ? print("-W /vmlinuz is writable by real uid/gid\n") : print("-W /vmlinuz is not writable by real UID/ GID\n"); -wCompliance
SyntaxCategory named unary operator (file test) Arguments handle Arguments filename Arguments none Return Value 1 (true) '' (false) DefinitionThe file test operator takes one file handle or filename as an argument. It returns 1 (true) if the file is writable by the effective UID/GID. It returns '' (false) otherwise. For the superuser it always returns true. All file test operators can take a special argument underscore, which means that the test is carried out on the same file handle as the last file test, stat(), or lstat() call. If no argument is supplied, $_ is used. Example(-w "/vmlinuz") ? print("-w /vmlinuz is writable by effective uid/gid\n") : print("-l /vmlinuz is not writable by effective uid/gid\n"); -XCompliance
SyntaxCategory named unary operator (file test) Arguments handle Arguments filename Arguments none Return Value 1 (true) '' (false) DefinitionThe file test operator takes one file handle or filename as an argument. It returns 1 (true) if the file is executable by the real UID/GID. It returns '' (false) otherwise. For the superuser it always returns true. All file test operators can take a special argument underscore, which means that the test is carried out on the same file handle as the last file test, stat(), or lstat() call. If no argument is supplied, $_ is used. Example(-X _) ? print("-X /bin/ls is executable by real uid/gid\n") : print("-X /bin/ls is not executable by real uid/gid\n"); -xCompliance
SyntaxCategory named unary operator (file test) Arguments handle Arguments filename Arguments none Return Value 1 (true) '' (false) DefinitionThe file test operator takes one file handle or filename as an argument. It returns 1 (true) if the file is executable by the effective UID/GID. It returns '' (false) otherwise. For the superuser it always returns true. All file test operators can take a special argument underscore, which means that the test is carried out on the same file handle as the last file test, stat(), or lstat() call. If no argument is supplied, $_ is used. Example(-x "/bin/ls") ? print("-x /bin/ls is executable by effective uid/gid\n") : print("-x /bin/ls is not executable by effective uid/gid\n"); -zCompliance
SyntaxCategory named unary operator (file test) Arguments handle Arguments filename Arguments none Return Value 1 (true) '' (false) DefinitionThe file test operator takes one file handle or filename as an argument. It returns 1 (true) if the file has zero size. It returns '' (false) otherwise. All file test operators can take a special argument underscore, which means that the test is carried out on the same file handle as the last file test, stat() or lstat() call. If no argument is supplied, $_ is used. Example(-z "/vmlinuz") ? print("-z /vmlinuz has zero size\n") : print("-z /vmlinuz does not have zero size\n"); absCompliance
SyntaxCategory named unary operator (numeric) Arguments numeric value Return Value numeric Definition
This function returns the absolute value of its argument (it ignores
Exampleprint("abs(-10) = ",abs(-10),"\n"); acceptCompliance
SyntaxCategory list operator (socket) Arguments newsocket, genericsocket Return Value integer (address of socket), '' (false) DefinitionThis function performs low-level UNIX socket call accept(). AlarmCompliance29
SyntaxCategory named unary operator (process) Arguments integer (seconds) Return Value integer (seconds to previous alarm) DefinitionThis function sets up a UNIX SIGALRM signal to be generated in the number of seconds specified. It is possible for Perl to trap such signals by calling specific signal handling subroutines, such as trap(). Subseqent calls reset the alarm() time, retaining the number of seconds which were needed before the previous SIGALRM would have been generated. A call with zero seconds as an argument cancels the current alarm(). Exampleprint("alarm(10) ",alarm(10), " (to illustrate it needs to trapped c.f. trap)\n"); atan2Compliance
SyntaxCategory list operator (numeric) Arguments numeric, numeric Return Value numeric DefinitionThe atan2 function returns the arctangent of the arguments. Exampleprint("atan2(60,2) = ",atan2(60,2),"\n"); bindCompliance
SyntaxCategory list operator (socket) Arguments sockethandle, numeric (network address) Return Value 1 (true) '' (false) DefinitionThis function binds a network address to the socket handle, see the UNIX bind() call. BinmodeCompliance
SyntaxCategory named unary operator (i/o) Arguments handle Return Value 1 (success) or undefined (error) DefinitionOn systems that distinguish between text and binary files, this function forces binary mode treatment of the given file handle. In systems which do make the distinction, text files have the end of line characters (Carriage Return, Linefeed) automatically translated to the UNIX end of line character (Linefeed) when reading from the file (and vice versa when writing to the file); binary mode files do not have this automatic transformation. Exampleopen(FIL,"file.dat"); binmode(FIL); blessCompliance
SyntaxCategory list operator (class) Arguments variable Arguments variable, classname Return Value reference Definition
This function assigns a class to the referenced object. This class
is either explicitly stated in the call, or the name of the current
package is used if a second argument is not used in the call.
The reference is returned.
Example$tmp = {}; bless $tmp, ATMPCLASS; print "bless() \$tmp is now in class ",ref($tmp),"\n"; callerCompliance
SyntaxCategory named unary operator (scope) Arguments expression Arguments none Return Value 1 (true) '' (false) Return Value (package, filename, line) DefinitionThis function is used to test the current scope of a subroutine call. If evaluated in a scalar context, it returns 1 or '' depending on if the current code has been called as a subroutine (this includes code which is included using a require() or an eval() call). In an array context it supplies details of the calling context in a list comprising the package name, filename, and line of the call. Examplesub testcaller { ($package, $file, $line) = caller; } &testcaller; print "caller() Package=$package File=$file Line=$line \n"; chdirCompliance
SyntaxCategory named unary operator (files) Arguments expression Arguments none Return Value 1 (true) '' (false) DefinitionThis function changes the current directory to the directory specified. If no argument is given this call changes the current directory to be the home directory of the current user. It returns 1 upon success and '' otherwise. Examplechdir("/") ? print("It worked.\n") : print("It didn't work.\n"); chmodCompliance
SyntaxCategory list operator (files) Arguments list Return Value numeric DefinitionThe first element in the list is the UNIX octal number representing the file permission. This function applies the mode specified by the octal number to all the files in the list that follows. It returns the number of files successfully modified. Exampleprint "chmod() changed ", chmod(0744,"/tmp/test1.txt","/tmp/test2.txt")," files.\n"; chompCompliance
SyntaxCategory list operator (string) Arguments list Arguments variable Arguments none Return Value numeric DefinitionThis is an alternative to the chop() function. It removes characters at the end of strings corresponding to the $INPUT_LINE_SEPARATOR ($/). It returns the number of characters removed. It can be given a list of strings upon which to perform this operation. When given no arguments, the operation is performed on $_. Example$tmp="Aaagh!\n"; $ret = chomp $tmp; print("chomp() ", $tmp, " returned ", $ret, "\n"); chopCompliance
SyntaxCategory list operator (string) Arguments list Arguments variable Arguments none Return Value character DefinitionThis function removes the last character of a string and returns that character. If given a list of arguments, the operation is performed on each one and the last character chopped is returned. Example$tmp = "1234"; $ret = chop $tmp; print("chop() ", $tmp, " returned ", $ret, "\n");
ChownCompliance
SyntaxCategory list operator (files) Arguments list Return Value numeric DefinitionThis function changes the ownership of the specified files. The first two elements of the list define the user ID and the group ID to set this ownership; the subsequent items in the list are the file names that are changed. The return value is the number of files successfully changed. Exampleprint("chown() "); chown(1,1,"/tmp/test1.txt") ? print("Worked\n") : print("Didn't work\n"); chrCompliance
SyntaxCategory named unary operator (string) Arguments numeric Return Value character Definition
This function returns the character indicated
by the numeric Example$E = chr(69); print("chr() $E \n"); chrootCompliance
SyntaxCategory named unary operator (files) Arguments directoryname Arguments none Return Value 1 (true) '' (false) Definition
This function is equivalent to the UNIX chroot()
function. Given a directoryname,
this directory is treated as the root directory by all subsequent
file system references, thus effectively hiding the rest of the
file system outside the specified directory. This restriction
applies to all subprocesses of the current process as well.
Exampleprint("chroot() "); chroot("/") ? print("Worked.\n") : print("Didn't work.\n"); closeCompliance
SyntaxCategory named unary operator (files) Arguments handle Return Value 1 (true) '' (false) DefinitionThis function closes the file opened with the file handle. This operation flushes all buffered output. If the file handle refers to a pipe, the Perl program waits until the process being piped has finished. Exampleopen(INF,"/tmp/test1.txt"); $ret = close(INF); print("close() Returned ",$ret," on success\n"); closedirCompliance
SyntaxCategory named unary operator (file) Arguments handle Return Value 1 (true) '' (false) DefinitionThis function closes the directory opened by opendir() by specifying the relevant directory handle. Exampleopendir(IND,"/tmp"); $ret = closedir(IND); print("closedir() Returned ",$ret," on success\n"); connectCompliance
SyntaxCategory list operator (socket) Arguments socket, name Return Value 1 (true) '' (false) DefinitionThis function is equivalent to the UNIX function call, which initiates a connection with a process, assuming that the process that is connected is waiting to accept. ContinueCompliance
SyntaxCategory flow control Arguments block Return Value N/A Definition45A continue block is a syntax structure that allows a condition to be attached to another block (normally a while block). Any statements in the continue block are evaluated before the attached block is repeated. Example$i=0; print "continue() "; while ($i<10) { if ($i % 2) { print "${i}o "; next; } else {print "${i}e ";} } continue {$i++} print "\n"; cosCompliance46
SyntaxCategory named unary operator (numeric) Arguments expression Return Value numeric DefinitionThis function returns the cosine value of the numeric expression supplied as an argument. Exampleprint "cos() ",cos(60),"\n"; cryptCompliance
SyntaxCategory list operator Arguments string, string Return Value string DefinitionThis function is equivalent to the crypt() UNIX call (where available). It encrypts a string (the first argument) using a key (usually the first two letters of the first string itself) and returns the encrypted string. Exampleprint "crypt() Password PA: ",crypt("Password","PA"),"\n"; dbmcloseCompliance
SyntaxCategory named unary operator (i/o) Arguments arrayname Return Value 1 (true) '' (false) Definition
This function undoes the linking of an associative array to a
DBM file (see dbmopen()).
DbmopenCompliance
SyntaxCategory list operator (i/o) Arguments arrayname, dbname, mode Return Value fatal error if dbm not supported (Perl 4) Definition
This function links the associative array referred to by arrayname,
to the DBM database (or equivalent) referred to by dbname
(this name should not include the suffix). If the database does
not exist, a new one with the specified mode will be opened (the
mode being an octal chmod()
style file protection).
DefinedCompliance
SyntaxCategory named unary operator (misc) Arguments expression Return Value 1 (true) '' (false) DefinitionThis function returns a Boolean value depending on whether the argument is defined or not. There is a subtle distinction between an undefined and a defined null value. Some functions return undefined null to indicate errors, while others return a defined null to indicate a particular result (use a comparison with the null string to test for this, rather than using defined()) Example@iexist = (1,2,3); print("defined() The array \@iexist "); defined @iexist ? print("exists.\n") : print("does not exist.\n"); deleteCompliance
SyntaxCategory named unary operator (hash) Arguments expression Return Value value Definition51Use this function to delete an element from a hash array, given the key for the element to delete, returning the value of the deleted element. Example%Hash = (1, One, 2, Two, 3, Three); print("delete() Deleted ",delete($Hash{1}),"\n"); dieCompliance
SyntaxCategory list operator (i/o) Arguments list Return Value errorlevel DefinitionThis function terminates execution of the Perl script when called printing the value of the list argument to STDERR (as if called with print(STDERR, list)). The exit value is the current value of $OS_ERROR ($!), which may have been set by a previous function. If this has a value of zero it returns $CHILD_ERROR ($?). If this is zero, it exits with errorlevel 255. If the error message string specified by the list does not end in a newline, the text "at $PROGRAM_NAME at line line, where line is the line number of the Perl script. Exampledie("die() Now we can give an example of die()...exiting"); doCompliance
SyntaxCategory (flow) Arguments block Arguments subroutine(list) Arguments expression Return Value special DefinitionThis is a syntax structure that allows repeated execution of a block of statements. The value returned is the result of the last statement in the block. Normally an exit condition is supplied after the block. The second form where the argument is subroutine() is a depreciated form. The third form executes the contents of the file name specified by the expression (but it is better to use use() or require() instead, because this has better error checking). Example$i=1; print("do "); $return = do { print $i, " "; $i++; } until $i==3; print("Returned $return\n"); dumpCompliance
SyntaxCategory named unary operator (misc) Arguments label Return Value N/A DefinitionThis function causes the program to create a binary image core dump. This then allows the dumped image to be reloaded using the undump() function (if supported) which can effectively allow the use of precompiled Perl images. When reloaded, the program begins execution from the label specified. It is possible to set up a program which initializes data structures to dump() after the initialization so that execution is faster when reloading the dumped image. EachCompliance
SyntaxCategory named unary operator (hash) Arguments variable Return Value key, value DefinitionThis function allows iteration over the elements in an associative array. Each time it is evaluated, it returns another list of two elements (a key, value pair from the associative array). When all the elements have been returned, it returns a null list. Example%NumberWord = (1, One, 2, Two, 3, Three); print("each() "); while (($number,$wordform)=each(%NumberWord)) { print("$number:$wordform "); } print("\n"); endgrentCompliance
SyntaxCategory (system files) Arguments none Return Value 1 (true) '' (false) DefinitionThis function closes the /etc/group file used by getgrent() and other group related functions. It is equivalent to the UNIX system call. Example($name,$pw,$gid,@members)=getgrent(); $returned = endgrent(); print("endgrent() Closes /etc/group [$name,$gid]", " file returning $returned.\n"); endhostentCompliance
SyntaxCategory (system files) Arguments none Return Value 1 (true) '' (false) DefinitionThis function closes the TCP socket used by name server queries gethostbyname() and host related functions. It is equivalent to the UNIX system call. Example$host = gethostbyname("lynch"); $returned = endhostent(); print("endhostent() Closes /etc/hosts [$host]", " returning $returned.\n"); endnetentCompliance
SyntaxCategory (system files) Arguments none Return Value 1 (true) '' (false) DefinitionThis function closes the /etc/networks file used by getnetent() and network related functions. This function is equivalent to the UNIX system call. Example($name,$alias,$net,$net) = getnetent(); $returned = endnetent(); print("endnetent() Closes /etc/networks [$name]", " returning $returned.\n"); endprotoentCompliance
SyntaxCategory (system files) Arguments none Return Value 1 (true) '' (false) Definition
This function closes the /etc/protocols
file used by getprotoent()
and protocol related functions. It is equivalent Example($name, $alias, $protocol) = getprotoent(); $returned = endprotoent(); print("endprotoent() Closes /etc/protocols ", "[$name,$alias,$protocol] file returning $returned.\n"); endpwentCompliance
SyntaxCategory (system files) Arguments none Return Value 1 (true) '' (false) DefinitionThis function closes the /etc/passwd file used by getpwent() and password related functions. It is equivalent to the UNIX system call. Example($name,$pass,$uid,$gid,$quota,$name,$gcos,$logindir,$shell) = getpwent(); $returned = endpwent(); print("endpwent() Closes /etc/passwd [$logindir,$shell] ", "file returning $returned.\n"); endserventCompliance
SyntaxCategory (system files) Arguments none Return Value 1 (true) '' (false) DefinitionThis function closes the /etc/servers file used by getservent() and related functions. It is equivalent to the UNIX system call. Example($name,$aliases,$port,$protocol) = getservent(); $returned = endservent(); print("endservent() Closes /etc/servers [$name]", " file returning $returned.\n"); eofCompliance
Syntax62Category named unary operator (i/o) Arguments handle Arguments () Arguments none Return Value 1 (true) '' (false) DefinitionThis function tests if the file pointer to file specified by the file handle is at the and of the file. This is done by reading the next character and then undoing this operation (so is only suitable on files where this can be done safely). If no argument is supplied the file tested is the last file that was read. If the empty list is supplied then this tests if all the last file suppiled an argument to the Perl script are eof() (that is, it can be used as a termination condition in a while loop). Exampleopen INF, "/tmp/test1.txt"; if (eof INF) {print "eof() TRUE\n";} else {print "eof() FALSE\n";} close INF; evalCompliance
SyntaxCategory named unary operator (flow) Arguments expression Arguments block Arguments none Return Value special Definition
This function treats the expression like a Perl program and executes
it returning the return value
of the last statement executed. As the context of this execution
is the same as that of the script itself, variable definitions
and subroutine definitions persist. Syntax errors and runtime
errors (including die())
are trapped and an undefined result is returned. If such an error
does occur, $EVAL_ERROR ($@)
is set. If no errors are found, $@
is equal to a defined null string. If no expression is supplied,
$_ is the default argument.
If the block syntax is used, the expressions in the block are
evaluated only once within the script, which may be more efficient
for certain situations.
Example$ans = 3; eval "$ans = ;"; if ($@ eq "") {print "eval() returned success.\n";} else {print "eval() error: $@";} execCompliance
SyntaxCategory list operator (process) Arguments list Return Value N/A DefinitionThis function passes control from the script to an external system command. There is no retain from this call so there is no return value. Note that system() calls external commands and does return to the next line in the calling Perl program. This is equivalent to the UNIX system call execvp(). Exampleexec("cat /etc/motd"); existsCompliance
SyntaxCategory named unary operator (hash) Arguments expression Return Value 1 (true) '' (false) DefinitionThis function tests if a given key value exists in an associative array, returning a Boolean value. Example%test = ( One, 1, Two, 2); if (exists $test{One}) {print "exists() returned success.\n";} else {print "exists() returned an error.\n";} exitCompliance
SyntaxCategory named unary operator (flow) Arguments expression Arguments none Return Value value DefinitionThis function evaluates the expression given as an argument and exits the program with that error. The default value for the error is 0 if no argument is supplied. Note that die() allows an error message. Exampleexit(16); expCompliance
SyntaxCategory named unary operator (numeric) Arguments expression Arguments none Return Value numeric DefinitionThis function returns the natural log base (e) to the power of expression (or of $_ if none specified). Exampleprint "exp() e**1 is ",exp(1),"\n"; fcntlCompliance
SyntaxCategory list operator (i/o) Arguments handle, function, packed_parameters DefinitionThis function is equivalent to the UNIX fnctl() call. In Perl 5, use the fntcl module. In Perl 4, there should be some mechanism for linking the Perl functions to the system functions. This is usually executed when Perl is installed. FilenoCompliance
SyntaxCategory named unary operator (i/o) Arguments handle Return Value descriptor DefinitionThis function returns the file descriptor given a file handle. Exampleprint("fileno() ",fileno(INF),"\n"); flockCompliance
SyntaxCategory list operator (i/o) Arguments handle, operation Return Value 1 (true) '' (false) DefinitionThis calls the UNIX flock() function to access file locks. The handle is a Perl file handle. The operation is any valid flock() operation: place exclusive lock, place shared lock, and unlock. These operations are represented by numeric values. ForkCompliance
SyntaxCategory (process) Arguments none Return Value pid DefinitionThe fork function calls the UNIX fork() function or equivalent to fork a subprocess at this point. Returns the process ID (pid) of the child process to the calling process; returns 0 to the child process itself. The calling program should wait() on any child process it forks to avoid creating zombie processes. Example$pid = fork; # Child only prints this if ($pid != 0) { print("fork() Forking a process duplicates o/p: $pid \n"); } waitpid($pid,0); # Child exits here if ($$ != $origpid) { die; } formatCompliance
SyntaxCategory list operator (i/o) Arguments format DefinitionThis function declares an output format specification. These formats are used in conjunction with the write() function to control the output of variables and text to conform to a standard layout structure. Normally, the specification includes some variables, specifying how many characters to output and whether to justify these left, right or centered. When write() is called, the actual values of the variables are used. This is useful for printing simple text reports and tables. The format specification itself is terminated by a period on a line by itself. The specification itself is in pairs of lines, the first describing the layout, and the second describing the variables to use in this layout. Exampleformat STDOUT = format() @>>>>>>> @>>>>>>> @>>>>>>> $t1, $t2, $t3 . $t1 = One; $t2 = Two; $t3 = 3; write; formlineCompliance
SyntaxCategory list operator (i/o) Arguments picture, list DefinitionThis function is not usually called explictly (it is an implicit part of the format mechanism). It allows direct manipulation of the format process by adding values to the format accumulator ($^A). Example$tmp = formline <<'FINISH', Alpha, Beta, Gamma; formline() @>>>>>> @>>>>>> @>>>>>> FINISH print $^A; getcCompliance
SyntaxCategory named unary operator (i/o) Arguments handle Arguments none Return Value character DefinitionThis function returns the next character in specified file handle. The file defaults to STDIN if none is specified. If there are no more characters, null is returned. Exampleopen INF, "/etc/motd"; print "getc() ",getc(INF),"\n"; close INF; getgrentCompliance
SyntaxCategory list operator (system files) Arguments none Return Value name DefinitionThis returns the next group name (or undefined) in the /etc/group system file. In a list context, it returns extra information taken from this file (or null list). This function is equivalent to the UNIX system call getgrent(). Example($name,$pw,$gid,@members)=getgrent(); print("getgrent() Examines /etc/group [$name,$gid] file.\n"); getgrgidCompliance
SyntaxCategory named unary operator (system files) Arguments gid Return Value name DefinitionThis function returns the next group name (or undefined) in the /etc/group system file with the supplied group ID (gid). In a list context, it returns extra information taken from this file (or null list). Equivalent to the UNIX system call getgrgid(). Example($grname,$grpw,$gid,@members) = getgrgid(0); print("getgrgid() Returns group name given GID [$grname]\n"); getgrnameCompliance
SyntaxCategory named unary operator (system files) Arguments name Return Value gid DefinitionThis function returns the next group ID, gid, (or undefined) in the /etc/group system file with the supplied group name. In a list context, it returns extra information taken from this file (or null list). It is equivalent to the UNIX system call getgrname(). Example($grname,$grpw,$gid,@members) = getgrnam("root"); print("getgrnam() Returns group GID given name [$gid]\n"); gethostbyaddrCompliance
SyntaxCategory named unary operator (system files) Arguments address Return Value name DefinitionIt returns the host name, (or undefined) in the /etc/hosts system file (or via a Domain Name Server lookup) with the supplied host address. In a list context, The function returns extra information taken from this file (or null list). It is equivalent to the UNIX system call gethostbyaddr(). Example (Perl 5 only)use Socket; @a=(140,203,7,103); $addr=pack('C4',@a); ($name,$alias,$adrtype,$length,@address)=gethostbyaddr($addr,AF_INET); print("gethostbyaddr() [$alias].\n"); gethostbynameCompliance
SyntaxCategory named unary operator (system files) Arguments name Return Value address DefinitionThis function returns the host address, (or undefined) in the /etc/hosts system file (or via a Domain Name Server lookup) with the supplied host name. In a list context, it returns extra information taken from this file (or null list). This function is equivalent to the UNIX system call gethostbyname(). Example($name,$alias,$adrtype,$length,@address)=gethostbyname("lynch"); print("gethostbyname() [$alias].\n"); gethostentCompliance
SyntaxCategory (system files) Arguments none Return Value name Definitiongethostent returns the next host name, (or undefined) in the /etc/hosts system file (or via a Domain Name Server lookup). In a list context, it returns extra information taken from this file (or null list). This function is equivalent to the UNIX system call gethostent(). Example($name,$alias,$adrtype,$length,@address)=gethostbyname("lynch"); print("gethostent() [$alias].\n"); getloginCompliance
SyntaxCategory (system files) Arguments none Return Value name DefinitionThis function returns the current login name from the /etc/utmp system file. Exampleprint ("getlogin() ",getlogin(),"\n"); getnetbyaddrCompliance
SyntaxCategory (system files) Arguments address Return Value name Definitiongetnetbyaddr returns the network name from the /etc/networks system file given a network address. In a list context, it returns extra information from this file. This function is equivalent to UNIX's getnetbyaddr() call. Example($name,$alias,$addrtype,$net) = getnetent(); ($name,$alias,$addrtype,$net) = getnetbyaddr($net,$addrtype); print("getnetbyaddr() Reads /etc/networks [$name]\n"); getnetbynameCompliance
SyntaxCategory named unary operator (system files) Arguments name Return Value address DefinitionReturns the network address from the /etc/networks system file, given a network name. In a list context returns extra information from this file. Equivalent to the UNIX getnetbyname() call. Example($name,$alias,$addrtype,$net) = getnetbyname("localnet"); print("getnetbyname() Reads /etc/networks [$name]\n"); getnetentCompliance
SyntaxCategory (system files) Arguments none Return Value name DefinitionThis function returns the next network name from the /etc/networks system file. In a list context, it returns extra information from this file. getnetent is equivalent to the UNIX getnetent() call. Example($name,$alias,$addrtype,$net) = getnetent(); print("getnetent() Reads /etc/networks [$name,$addrtype]\n"); getpeernameCompliance
SyntaxCategory named unary operator (socket) Arguments socket Return Value name Definitiongetpeername is equivalent to the UNIX system getpeername() system call. getpgrpCompliance
SyntaxCategory named unary operator (process) Arguments pid Return Value gid DefinitionThis function returns the group ID (gid) of the process with the process ID (pid). Exampleprint("getpgrp() ",getpgrp(0),"\n"); getppidCompliance
SyntaxCategory (process) Arguments none Return Value pid Definitiongetppid returns the process ID (pid) of the parent process of the current process. Exampleprint("getppid() ",getppid(),"\n"); getpriorityCompliance
SyntaxCategory list operator (process) Arguments type, id Return Value priority DefinitionThis function calls the UNIX getpriority() function. The type is one of PRIO_PROCESS, PRIO_PGGRP, and PRIO_USER. The id is the relevant ID for this (pid for PRIO_PROCESS, pid for PRIO_PGGRP, uid for PRIO_USER). If zero is used as the id, the current process, process group, or user is used. Exampleprint("getpriority() ",getpriority(0,0),"\n"); getprotobynameCompliance
SyntaxCategory named unary operator (system files) Arguments name Return Value protocol DefinitionThis function returns the protocol number from the /etc/protocols system file, given the protocol name. In a list context, it returns extra information from this file. getprotobyname is equivalent to the UNIX getprotobyname() call. Example($name, $alias, $protocol) = getprotobyname("IP"); print("getprotobyname() /etc/protocols [$name,$alias,$protocol].\n"); getprotobynumberCompliance
SyntaxCategory named unary operator (system files) Arguments protocol Return Value name DefinitionThis function returns the protocol name from the /etc/protocols system file, given the protocol number. In a list context, it returns extra information from this file. getprotobynumber is equivalent to the UNIX getprotobynumber() call. Example($name, $alias, $protocol) = getprotobynumber(0); print("getprotobynumber() /etc/protocols [$name,$alias,$protocol].\n"); getprotoentCompliance
SyntaxCategory (system files) Arguments none Return Value name DefinitionThis returns the next protocol name from the /etc/protocols system file. In a list context, it returns extra information from this file. This function is equivalent to UNIX's getprotoent() call. Example($name, $alias, $protocol) = getprotoent(); print("getprotoent() Closes /etc/protocols [$name,$alias,$protocol].\n"); getpwentCompliance
SyntaxCategory (system files) Arguments none Return Value name Definitiongetpwent returns the user name from the next entry in the /etc/passwd system file. In a list context, it returns extra information from this file. This function is equivalent to the UNIX getpwent() call. Example($name,$pass,$uid,$gid,$quota,$name,$gcos,$logindir,$shell) = getpwent(); print("getpwent() /etc/passwd [$logindir,$shell].\n"); getpwnamCompliance
SyntaxCategory named unary operator (system files) Arguments name Return Value uid DefinitionThis function returns the user ID (uid) from the /etc/passwd system file given the user name. In a list context, it returns extra information from this file. It is equivalent to the UNIX getpwnam() call. Example($name,$pass,$uid,$gid,$quota,$name,$gcos,$logindir,$shell) = getpwnam("root"); print("getpwnam() /etc/passwd [$logindir,$shell].\n"); getpwuidCompliance
SyntaxCategory named unary operator (system files) Arguments uid Return Value name Definitiongetpwiud returns the user name from the /etc/passwd system file given the user ID (uid). In a list context, getpwuid returns extra information from this file. This function is equivalent to the UNIX getpwnam() call. Example($name,$pass,$uid,$gid,$quota,$name,$gcos,$logindir,$shell) = getpwuid(0); print("getpwuid() /etc/passwd [$logindir,$shell].\n"); getservbynameCompliance
SyntaxCategory list operator (system files) Arguments name, protocol Return Value port Definitiongetservbyname returns the port number of the service from the /etc/services system file given the service name and the protocol name. In a list context, it returns extra information from this file. This function is equivalent to UNIX's getservbyname() call. Example($name,$aliases,$port,$protocol) = getservbyname("tcpmux","tcp"); print("getservbyname() /etc/servers [$name].\n"); getservbyportCompliance
SyntaxCategory list operator (system files) Arguments port, protocol Return Value name Definitiongetservbyport returns the service name of the service from the /etc/services system file given the port number and the protocol name. In a list context, it returns extra information from this file. It is equivalent to the UNIX getservbyport() call. Example($name,$aliases,$port,$protocol) = getservbyport(512,"tcp"); print("getservbyport() Problem with this! [$name]\n"); getserventCompliance
SyntaxCategory (system files) Arguments none Return Value name DefinitionThis function returns the next service name of the service from the /etc/services system file. In a list context, it returns extra information from this file. It is equivalent to the UNIX getservet() call. Example($name,$aliases,$port,$protocol) = getservent(); print("getservent() /etc/servers [$name].\n"); getsocknameCompliance
SyntaxCategory named unary operator (socket) Arguments socket Return Value address DefinitionThis function returns the address of the socket. getsockoptCompliance
SyntaxCategory list operator (socket) Arguments socket, level, optionname Return Value option DefinitionThis function is equivalent to the UNIX getsockopt() system call and returns the socket option requested. However, if an error has happened, the function's return is undefined. globCompliance
SyntaxCategory named unary operator (files) Arguments expression Return Value list DefinitionThis function returns the list of files resulting from expanding the expression with any wildcards. This is equivalent to <*.*>. Example@files = glob("/tmp/*.txt"); print "glob() ",$files[1],"\n"; gmtimeCompliance
SyntaxCategory named unary operator (time) Arguments expression Arguments none Return Value list DefinitionGiven a time as an argument (measured in seconds since 1 Jan. 1970), gmtime returns a list of nine elements with that time broken down into seconds, minutes, hours, day of month, month, year, day of week, day of year, daylight saving enabled (daylight saving enabled is either 1 for on or 0 for off). If no argument is used, the current time is reported. If the system supports POSIX time zones, the time returned is localized for the Greenwich Mean Time. In a scalar context, the ctime() style output (a string describing the time in readable form) is returned. Example($sec,$min,$hour,$mday,$mon,$year,$wday,$ydat,$isdst) = gmtime(); print "gmtime() 19$year-$mon-$mday\n"; gotoCompliance
SyntaxCategory (flow) Arguments label Arguments expression Arguments &name Return Value N/A DefinitionThe first form transfers control flow in the program to the specified label. The second allows the evaluation of an expression to supply the label name to transfer control to. The third form is a way of passing control from one subroutine to another subroutine so that, to the original caller, it appears that the second subroutine was called directly. Exampleprint "goto "; $count = 1; TESTGOTO: { print $count, " "; $label = "TESTGOTO"; if ($count < 2) { $count++; goto $label; } else { goto FINISH;} } FINISH: print "\n"; grepCompliance
SyntaxCategory list operator (lists) Arguments expression, list Arguments block, list Return Value list DefinitionThis function evaluates the expression or block for each of the elements in the supplied list, returning a list of the elements that were evaulated as true. The most common use for this is with a pattern match operation as the expression, and a list of strings to be processed. Example@a = ("One","Two","Three","Four","Five"); print("grep(), ",grep(/^T.*/,@a), "\n"); hexCompliance
SyntaxCategory named unary operator (numeric) Arguments expression Return Value numeric DefinitionThis function evaluates the expression as a hexadecimal string and returns the decimal equivalent. Exampleprint("hex() ",hex("ff"), "\n"); importCompliance
SyntaxCategory list operator (scope) Arguments list Return Value 1 (true) '' (false) DefinitionIn the Perl 5 module system, each module has a local import() method. This is called when use() includes modules. indexCompliance
SyntaxCategory list operator (string) Arguments string substring Arguments string substring position Return Value position Definitionindex returns the position in the supplied string where the substring first occurs. If a position is supplied as an argument, the search begins at this element (thus repeated calls can find all occurrences if the found position is passed back as the argument to the subsequent calls). If the substring is not found, the return value is -1. All array element numbers are based on $[, which is normally set to zero. If this value is altered it will change the way index() works. This is because index will start its search from $[ if no position argument is supplied, and it will return $[-1 when there is no match found. Example$ans1 = index("abcdefghijiklmdef:-)","def"); $ans2 = index("abcdefghijiklmdef","def",$ans1+3); print("index() def is at $ans1 and next at $ans2\n"); intCompliance
SyntaxCategory named unary operator (numeric) Arguments expression Arguments none Return Value integer DefinitionThis function returns the integer part of the expression. It uses $_ as the argument if none is specified. Exampleprint("int() ",int(345.678), "\n"); ioctlCompliance
SyntaxCategory list operator (files) Arguments handle, function, parameter Return Value numeric DefinitionThis function calls the UNIX ioctl() function with the specified packed parameter. It returns undefined if the operating system returns -1. It returns the string 0 but true if the operating system returns 0. Otherwise, it returns the value returned by the operating system. joinCompliance
SyntaxCategory list operator (lists) Arguments expression, list Return Value string DefinitionThis function returns the string comprising each element in the list joined with the string expression. Example@listone = (0, 1, 2, 3); print("join() ",join("-",@listone),"\n"); keysCompliance
SyntaxCategory named unary operator (hash) Arguments array Return Value list DefinitionThis function returns a list comprising each key in the associative array passed as a parameter. In a scalar context, the number of keys is returned. The returned list is ordered by the internal storage requirements, so it is often useful to sort this array before processing. Example%assocone = ( One, 1, Two, 2, Three, 3, Four, 4 ); print("keys() ",join("-",keys(%assocone)),"\n"); killCompliance
SyntaxCategory list operator (process) Arguments signal, list Return Value 1 (true) '' (false) DefinitionThis function kills the processes with the PIDs in the supplied list by sending the signal level specified. If the signal level is negative, the process groups are killed. lastCompliance
SyntaxCategory (flow) Arguments label Arguments none Return Value N/A DefinitionThis causes control to exit the loop specified by label (or the innermost loop if none is specified). Examplei=1; print("last() "); loop: while (I<10) { last loop if i=3; print(i); } print("\n"); lcCompliance
SyntaxCategory named unary operator (string) Arguments expression Return Value string DefinitionThis function returns the lowercase version of any supplied expression. Exampleprint"lc() ",lc("ABCDef"), "\n"; lcfirstCompliance
SyntaxCategory named unary operator (string) Arguments expression Return Value string DefinitionThis function returns the string with the first character of the expression lowercased. Exampleprint"lcfirst() ",lcfisrt("ABCDef"), "\n"; lengthCompliance
SyntaxCategory named unary operator (string) Arguments expression Arguments none Return Value numeric Definitionlength returns the length of the string specified by expression. If no expression is supplied, $_ is evaluated. Exampleprint("length() ",length("01234"),"\n"); linkCompliance
SyntaxCategory list operator (files) Arguments filename, linkname Return Value numeric DefinitionThis function creates a new link named after the second argument linking to the filename specified in the first argument; returns 1 or 0 for success or failure. Example$result = link("/usr/local",:"/tmp/link"); print("link() $result\n"); listenCompliance
SyntaxCategory list operator (socket) Arguments socket, queuesize Return Value 1 (true) '' (false) DefinitionThis is equivalent to the UNIX listen() system call. If you are using accepts on a socket, listen tells the system that it is available. localCompliance
SyntaxCategory named unary operator (scope) Arguments expression Return Value N/A DefinitionModifies all the variables listed to be local to the current block. If there is more than one element, the list must be enclosed in parentheses. Any errors would be syntax errors. Although local() does prevent pollution of the global namespace with variables in subroutines, my() is safer than local() because it also creates new copies of the variables for each recursive call of a subroutine. localtimeCompliance
SyntaxCategory named unary operator (time) Arguments expression Arguments none Return Value list DefinitionGiven a time as an argument (measured in seconds since 1 Jan. 1970), this function returns a list of nine elements with that time broken down into seconds, minutes, hours, day of month, month, year, day of week, day of year, daylight saving enabled (daylight saving enabled is either 1 for on or 0 for off). If no argument is used, the current time is reported. If the system supports POSIX time zones, the time returned is localized for the current time zone. In a scalar context, the ctime() style output is returned (a string describing the time in readable form). Example($sec,$min,$hour,$mday,$mon,$year,$wday,$ydat,$isdst) = localtime(); print "localtime() 19$year-$mon-$mday\n"; logCompliance
SyntaxCategory named unary operator (numeric) Arguments expression Arguments none Return Value numeric DefinitionThis returns the logarithm (using the natural logarithm base) of the expression (or of $_ if none specified). Exampleprint("log() ",log(2.5),"\n"); lstatCompliance
SyntaxCategory named unary operator (files) Arguments handle Arguments expression Return Value list DefinitionThe lstat function returns the file statistics of the file pointed to by the file handle (or a file handle produced by evaluating the expression). This is equivalent to stat(), but if the file is a symbolic link, the statistics are generated for the symbolic link itself rather than the file being linked to. Note that, like the file test operators, lstat() can take a special argument underscore, which means that the test is carried out on the same file handle as the last file test, stat(), or lstat() call. Example($device,$inode,$mode,$nlink,$uid,$gid,$rdev,$size, $atime,$mtime,$ctime,$blksize,$blocks) = lstat("/tmp/link"); print("lstat() $device, $inode, $ctime \n"); m//Compliance
SyntaxCategory named unary operator (pattern) Arguments m/<pattern>/<optionlist> Arguments /<pattern>/<optionlist> Return Value 1 (true) '' (false) DefinitionThis function searches the default string for the pattern using regular expression pattern matching. It returns 1 if a match is found. Otherwise, '' is returned. The default string can be assigned to the match using either the =~ or !~ operators; otherwise, it is $_. Example$_ = "Happy MaN"; print "m// ",/n$/i,"\n"; mapCompliance
SyntaxCategory list operator (list) Arguments block list Arguments expression, list Return Value list DefinitionThis function evaluates the specified expression (or block) for each individual member of the specified list. This is done by assigning $_ to each member of the list and evaluating the expression (or block). The value returned is the list of all these results (not necessarily one Perl element of the list). Example@result = map($_+1,(0,1,2)); print("map() ",@result,."\n"); mkdirCompliance
SyntaxCategory list operator (files) Arguments filename, mode Return Value 1 or 0 DefinitionThe mkdir function creates a directory with a name specified by the filename, with the mode specified by the octal mode. If it fails, $OS_ERROR ($!) is set to operating system error. Exampleprint("mkdir() ",mkdir("/tmp/testdir",0777), "\n"); msgctlCompliance
SyntaxCategory list operator (System V) Arguments id, cmd, arg Return Value special DefinitionThis function is equivalent to the UNIX system call msgctl(), if supported, and provides a variety of message control operations as specified by CMD. msggetCompliance
SyntaxCategory list operator (System V) Arguments key, flags Return Value special DefinitionThis function is equivalent to the UNIX system call msgget(), if supported, and returns the message queue identifier associated with key. msgrcvCompliance
SyntaxCategory list operator (System V) Arguments id, var.size, type, flags Return Value special DefinitionThis is equivalent to the UNIX system call msgrcv(), if supported. This function reads a message from the queue associated with the message queue identifier, specified by msqid, and places it in the structure pointed to by msgp. msgsndCompliance
SyntaxCategory list operator (System V) Arguments id, msg, flags Return Value special DefinitionThe msgsnd function is equivalent to the UNIX system call msgsnd(), if supported, and sends a message to the queue associated with the message queue identifier. myCompliance
SyntaxCategory named unary operator (scope) Arguments expression Return Value N/A DefinitionThis function declares each of the variables listed to be local() to the block. If more than one variable is specified, parentheses are required. The my() specification is stronger than the the local() specification because it not only stops pollution of the global namespace but also creates a stack frame for subroutine calls so that recursive calls will behave as one would expect with local variables. nextCompliance
SyntaxCategory named unary operator (flow) Arguments label Arguments none Return Value N/A DefinitionThis operator allows branching within a loop so that the execution skips onto the next instance of the loop. Exampleprint("next "); @array = ("a","b","c"); loop: foreach $elem (@array) { next if $elem =~ /^a/; print $elem; } print "\n"; noCompliance
SyntaxCategory list operator (module) Arguments module, list Return Value N/A DefinitionUsing this function, particularly useful when using pragmas, is the reverse of use(). Exampleuse integer; # code using integer arithmetic here no integer; # back to floating point arithmetic octCompliance
SyntaxCategory named unary operator (numeric) Arguments expression Return Value numeric DefinitionThis function evaluates the expression as an octal string and returns the decimal value. Exampleprint("oct() ",oct("88"), "\n"); openCompliance
SyntaxCategory list operator (files) Arguments handle, filename Arguments handle Return Value TRUE (non zero) or FALSE (undefined) DefinitionThis function opens a file using the specified file handle. The file handle may be an expression; the resulting value is used as the handle. If no filename is specified, a variable with the same name as the file handle is used (this should be a scalar variable with a string value referring to the filename). The filename string may be prefixed with the following values to indicate the mode:
The special file name - can refer to either STDIN (-) when reading) or STDOUT (>-), when writing. Exampleopen(FIL,"/tmp/notexist") || print("open() failed as file did not exist.\n"); opendirCompliance
SyntaxCategory list operator (files) Arguments handle, dirname Return Value 1 (true) '' (false) DefinitionOpens a directory handle for the directory name specified. If the dirname is an expression this can be evaluated to return a name. Exampleopendir (DIR, "/tmp/notexist") || print("opendir() diled as directory dod not exist.\n"); ordCompliance
SyntaxCategory named unary operator (string) Arguments expression Arguments none Return Value numeric DefinitionThis function returns the numeric ASCII code of the first character in the expression (or $_ if none specified). Exampleprint("ord() ",ord("A"), "\n"); packCompliance
SyntaxCategory list operator (records) Arguments template, list Return Value string Definition
This function returns a packed version of the data in the list
using the template to determine how it is coded. The template
comprises a sequence of characters, each specifying the data type
of the matching data item in the list.
A concise form of template can be used by appending a number after any letter to repeat that format specifier. For aA, the number uses one value and pads the rest. For bB, the number indicates the number of bits. For hH, the number indicates the number of nybbles. For P, the number indicates the size of the pointer structure. Using an asterisk in place of a number means to repeat the format specifier as necessary to use up all list values. Note that some packed structures may not be portable across machines (in particular, network and floating point formats). It should be possible to unpack the data using the same format specification with an unpack() call. ExampleUse Socketl @a=(140,203,7,103); $addr=pack('C4',@a); ($name,$alias,$adrtype,$length,@address)=gethostbyaddr ($addr,AF_INET);print("pack() ",@a, "packed as: $addr".\n"); packageCompliance
SyntaxCategory named unary operator (class) Arguments name Return Value N/A DefinitionCalling this function declares that all unqualified dynamic variables in the current block are in the scope of the specified package name. This is normally done in the header of a file to be included as a package or a module in other programs that require() or use(). Note that this does apply to variables declared as local() but not to variables declared as my(). pipeCompliance
SyntaxCategory list operator (process) Arguments readhandle, writehandle Return Value 1 (true) '' (false) DefinitionLinks named pipes like the UNIX function pipe(). popCompliance
SyntaxCategory name unary operator (array) Arguments variable Return Value value DefinitionThis function removes the top item from the array specified and returns that element. Example@a = (1,2,3,4); print("pop() ",pop(@a), "leaves ",@a,"\n"); posCompliance
SyntaxCategory named unary operator (pattern) Arguments variable Return Value numeric DefinitionReturns the offset that the last pattern match (m//g) reached when searching the scalar variable specified as an argument. It can be assigned to alter the bahavior of the next match. Example$name = "alpha1 alpha2 alpha3 alpha4"; $name =~ m/alpha/g; print("pos() ", pos($name), "\n"); posCompliance
SyntaxCategory list operator (i/o) Arguments handle, list Arguments list Arguments none Return Value 1 (true) '' (false) DefinitionPrints the list to the file represented by the file handle. If no file handle is specified the default file handle is STDOUT. This default file handle may be altered using the select() operator. If no list argument is specified, $_ is printed. Example$return = print "print() "; print "returns $return on success.\n"); printfCompliance
SyntaxCategory list operator (i/o) Arguments filehandle list Arguments list Return Value 1 (true) '' (false) DefinitionThis function uses the C printf format specifiers to control the printed output. It is equivalent to print filehandle, sprintf(list); As with print() the default file handle is STDOUT. Exampleprintf("printf() An integer printed with leading zeroes %05d.\n",9); pushCompliance
SyntaxCategory list operator (array) Arguments array, list Return Value numeric DefinitionThis appends the elements in the specified list on the end of the specified array and returns the new number of elements in the list. Example@a = (1); $num = push(@a,2,3,4,5); print("push() Added ",$num-1," elements to array:", @a,"\n"); q/STRING/Compliance
SyntaxCategory (string) Arguments q/string/ Return Value value DefinitionThis is a standard quote used to surpress special interpretation of characters giving a literal string. You can use single quotes 'string' or the letter q with delimiters. Any delimiter will do as long as it is not used in the string. The backslash character can be used to escape any reference to the delimiting character itself in the string. Exampleprint(q!q// The only special character is the delimiter itself \!!, "\n"); qq/STRING/Compliance
SyntaxCategory (string) Arguments qq/string/ Return Value value DefinitionThis is a double quote, used to allow interpolation of special characters within the string as required. You can use double quote "string" or the double qq with delimiters. The backslash character can be used to disable the special meaning of interpolated characters, including the delimiter itself. Example$newline = "\n"; print(qq!qq// double quoted with interpolation! $newline!); quotemetaCompliance
SyntaxCategory named unary operator (pattern) Arguments expression Return Value string Definitionquotemeta returns the value of the expression with all the metacharacters backslashed. Exampleprint(quotemeta("quotameta() I can use any metcharacter $ \ "),"\n"); qw/STRING/Compliance
SyntaxCategory (list) Arguments qw/string/ Return Value list DefinitionThis function returns a list of words in string. Spaces are used as delimiters in the string to produce this list. Exampleprint("qw// ",qw("1 2 3 4 5"),"\n"); qx/STRING/Compliance
SyntaxCategory (process) Arguments qx/string/ Return Value special DefinitionThis is a back quote, used to allow interpolation of special characters within the string as required and then execute the resulting command as a system command. You can use back quotes 'string' or the letters qx with delimiters. The backslash character can be used to disable the special meaning of interpolated characters, including the delimiter itself. The return value is the return value of the system() call. Exampleprint("qx// ",qx!du -s /tmp!); randCompliance
SyntaxCategory named unary operator (numeric) Arguments expression Arguments none Return Value numeric DefinitionThis function returns a real number between 0 and the number evaluated as expression (the upper limit is 1 if no expression is specified). The upper limit must be positive. As the function calls a pseudorandom generator, it should be possible to generate the same sequence of numbers repeatedly unless the initial seed value is altered with srand(). Exampleprint("rand(), ",rand,"\n"); readCompliance
SyntaxCategory list operator (i/o) Arguments handle, variable, length, offset Arguments handle, variable, length Return Value 1 (true) '' (false) DefinitionReads length bytes from file handle into variable (starting at offset if specified). It returns the number of bytes actually read. Exampleopen(INF,"/etc/services") || die "Error reading file, stopped"; read(INF,$result,10); print("read() $result \n"); close(INF) readdirCompliance
SyntaxCategory list operator (i/o) Arguments dirhandle Return Value lname DefinitionIn a list context, this function returns a list of the files in the directory specified by the directory handle. In a scalar context, it returns the next file name in the directory. Exampleopendir(DIR,"/tmp"); @file = readdir(DIR); print("readdir() ",@files, "\n"); readlinkCompliance
SyntaxCategory named unary operator (files) Arguments expression Arguments none Return Value value DefinitionThis function returns the value of the symbolic link specified by expression (or $_ if none specified). If symbolic links are not implemented, it gives a fatal error. If symbolic links are supported, but there is some system error, the error is returned in $OS_ERROR ($!). recvCompliance
SyntaxCategory list operator (socket) Arguments socket, variable, length, flags Return Value address DefinitionThe recv function is equivalent to UNIX system call recv() and receives a message on a socket. redoCompliance
SyntaxCategory (flow) Arguments label Arguments none Return Value N/A DefinitionThis function passes control directly to the label without executing any continue block. If no label is specified, the innermost loop is used. refCompliance
SyntaxCategory named unary operator (class) Arguments expression Return Value package DefinitionThis function returns the package of a bless()ed variable, TRUE if the variable is a reference, or FALSE. The return value for TRUE is actually the type of the variable (for example ARRAY, HASH, REF, SCALAR). Example$tmp = {}; bless $tmp, ATMPCLASS; print "ref() \$tmp is now in class ",ref($tmp),"\n"; renameCompliance
SyntaxCategory list operator (files) Arguments oldname, newname Return Value 1 (true) 0 (fail) DefinitionThis function renames files on the same file system from oldname to newname. Example$returned = rename("/tmp/test","/tmp/test2"); print("rename() returned $returned \n"); requireCompliance
SyntaxCategory named unary operator (module) Arguments expression Arguments none Return Value 1 (true) '' (false) DefinitionIf the expression is a scalar, the library specified by the filename is included (if it has not already been). In Perl 5, if the expression is numeric this requires that the version of Perl being used (in $PERL_VERSION or $[) is greater than or equal to the version specified. Note that Perl 5 also has the use() mechanism for including modules; use() is more robust than require. Examplerequire "cgilib.pl"; resetCompliance
SyntaxCategory named unary operator (misc) Arguments expression Arguments none Return Value 1 Definition
This function provides a way of resetting variables in the current
package (especially pattern match variables). The expression is
interpreted as a list of single characters. All variables starting
with those characters are reset. The letters are case sensitive
(as Perl variables are). Hyphens may be used to specify ranges
of variables to reset. If called without any argument, reset
simply resets all search matches.
reset A-Z; returnCompliance
SyntaxCategory list operator (flow) Arguments list Return Value list DefinitionThis function returns from a subroutine (or an eval()) with the value specified. Examplesub test { return 1; } $test = &test; print("return() Returned $test \n"); reverseCompliance
SyntaxCategory list operator (list) Arguments list Return Value list DefinitionThe reverse function returns the list given as an argument in reverse order. In a scalar context, it reverses the letters of its first argument. Example@a = (1,2,3); print("reverse() ",reverse(@a),"\n"); rewinddirCompliance
SyntaxCategory named unary operator (i/o) Arguments dirhandle Return Value 1 (true) '' (false) DefinitionWhen reading a directory using readdir(), it is possible to reset the directory to the first file name. Exampleopendir(DIR,"/tmp"); print("rewinddir() (a): " file: while ($file=readdir(DIR) { print $file, " "; } rewinddir(); print(" (b): " file: while ($file=readdir(DIR) { print $file, " "; } print("\n"); closedir(DIR); rindexCompliance
SyntaxCategory list operator (string) Arguments string, substring, position Arguments string, substring Return Value position DefinitionThis function is very similar to index() except that, instead of scanning for the substring from the first character in the string, it scans backwards from the last character. So it returns the starting position of the last occurrence of substring in string (scanning backwards from the specified position or from the end if no position is specified). Example$ans1 = rindex("abcdefghijiklmdef:-)","def"); $ans2 = rindex("abcdefghijiklmdef","def",$ans1+3); print("rindex() def is at $ans1 and next at $ans2\n"); rmdirCompliance
SyntaxCategory named unary operator (files) Arguments filename Return Value 1 or 0 DefinitionThis function deletes the directory specified (or $_) if it is empty and sets $OS_ERROR ($!) to the error value if there is a system error. s///Compliance
SyntaxCategory (pattern) Arguments s/pattern/replacement/options Return Value numeric Definition
This function searches the default string for pattern
(a regular expression) and replaces this with the replacement
string (the actual replacemnt behavior depends on the options).
It returns the number of replacements made. The default string
is set using either of the pattern binding operators (=~
or ¬~ ) or $_
is used if none have been bound. The valid options are
Example$oldstr = "abcdefABCDEFabcdefABCDEF"; $newstr= $oldstr; $str =~ s/abc/zzz/ig; print("s/// $oldstr became $newstr \n"); scalarCompliance
SyntaxCategory named unary operator (misc) Arguments expression Return Value value Definition
This operator forces the argument to be interpreted in a scalar
context, rather than as a list so that it can override the default
context if seekCompliance
SyntaxCategory list operator (i/o) Arguments handle, position, start Return Value 1 (true) '' (false) DefinitionThis function sets the file pointer to a specified offset position in a file. The offset is relative to the start that can have three values: 0 (start of file), 1 (current position), 2 (end of file). This allows the use of random access files, and the implementation of fast read algorithms (for example binary search techniques) on file handles, especially with fixed-length data where the offsets are easier to calculate. seekdirCompliance
SyntaxCategory list operator (i/o) Arguments dirhandle, position Return Value 1 (true) '' (false) DefinitionThis function allows the position in a directory to be reset to a position saved with telldir(). This is useful when processing directories with readdir(). selectCompliance
SyntaxCategory named unary operator (i/o) Arguments handle Arguments rbits, wbits, ebits, timeout Return Value handle DefinitionThis operator selects the default file handle used for I/O operations such as print() and write(). By default STDOUT is selected, but this function can select any other file handle to be the default instead. The return value is the currently selected file handle (before any change) so it is useful to assign this to a variable in order to be able to restore the original handle as the default at a later stage. The second form calls the UNIX system select() function. Exampleopen(OUT,"/tmp/t.out"); $return = select(OUT); print("This goues in /tmp/t.out.\n"); select($return); print("select() restored to STDOUT.\n"); semctlCompliance
SyntaxCategory list operator (System V) Arguments id, semnum, command, arg Return Value value DefinitionThis function is equivalent to the UNIX semctl() function. This is a semaphore control operation with several variables. semgetCompliance
SyntaxCategory list operator (System V) Arguments key, nsems, flags Return Value value DefinitionThis function is equivalent to the UNIX semget() function and returns the semaphore ID. semopCompliance
SyntaxCategory list operator (System V) Arguments key, opstring Return Value 1 (true) '' (false) DefinitionThe semop function is equivalent to the UNIX semop() function call and performs semaphore signalling and waiting functions. sendCompliance
SyntaxCategory list operator (socket) Arguments socket, message, flags, to Arguments socket, message, flags Return Value numeric DefinitionThis function is equivalent to the UNIX system send() function and sends a message socket. setgrentCompliance
SyntaxCategory (system files) Arguments none Return Value n/a DefinitionThis function rewinds the /etc/group file to the start of the file for subsequent accesses using getgrent(). Exampleprint("setgrent() ",setgrent(), "\n"); sethostentCompliance
SyntaxCategory named unary operator (system files) Arguments flag Return Value N/A DefinitionIf called with an argument of 1, this function tells the system to keep a TCP socket open for name server queries such as gethostbyname(). If this is not, then the name server queries use UDP datagrams. Exampleprint("sethostent() ",sethostent(1), "\n"); setnetentCompliance
SyntaxCategory named unary operator (system files) Arguments flag Return Value N/A DefinitionThis function rewinds the /etc/networks file used by getnetent() and other network related functions. If the flag has a value of 1, then the file is kept open between calls to getnetbyname() and getnetbyaddr(). print("setnetent() ",setnetent(1), "\n"); setpgrpCompliance
SyntaxCategory list operator (process) Arguments pid, pgrp Return Value 1 (true) '' (false) DefinitionThis function sets the current process group for the specified process (pid); if this is zero, the current process is set. setpriorityCompliance
SyntaxCategory list operator (proxess) Arguments type, id, priority Return Value 1 (true) '' (false) DefinitionThis function calls the UNIX setprority() function. The type is one of PRIO_PROCESS, PRIO_PGGRP, or PRIO_USER. The id is the relevent ID for this (pid, a pid for a group of processes, or uid). If 0 is used as the id, the current process, process group, or user is used. The priority is a number representing the level of priority (normally in the range 120 to 20) where the lower the priority, the more favorable the scheduling of the process by the operating system. Exampleprint("setpriority() ",setpriority(0,0,-20),"\n"); setprotoentCompliance
Category named unary operator (system files) Arguments flag Return Value 1 (true) '' (false) DefinitionThis function rewinds the /etc/protocols file used by getprotoent() and other protocol related functions. If the flag has a value of 1, then the file is kept open between calls to getprotobyname() and getnetbynumber(). Exampleprint("setprotoent() ",setprotoent(1), "\n"); setpwentCompliance
SyntaxCategory (system files) Arguments none Return Value 1 (true) '' (false) DefinitionThis function rewinds the /etc/passwd file used by getpwent() and other password related functions. Exampleprint("setpwent() ",setpwent(), "\n"); setserventCompliance
SyntaxCategory named unary operator (system files) Arguments flag Return Value 1 (true) '' (false) DefinitionThis function rewinds the /etc/services file used by getservent() and other service-related functions. If the flag has a value of 1, then the file is kept open between calls to getservbyname() and getnetbyport(). Exampleprint("setservent() ",setservent(1), "\n"); setsockoptCompliance
SyntaxCategory list operator (socket) Arguments socket, level, optname, optval Return Value 1 (true) '' (false) DefinitionThis function is equivalent to UNIX system call setsockopt() and sets the socket options. shiftCompliance
SyntaxCategory named unary operator (array) Arguments array Arguments none Return Value value DefinitionThis function takes the leftmost element from the array specified and returns that, reducing the array by one element. When no array is specified, the array of arguments passed to the Perl script, $ARGV, is used if the context is not in a subroutine; otherwise, the array of arguments passed to the subroutine, @_, is used. The return value is undefined if the array is empty. Exampleprint("shift() "); while ($arg = shift) { print($arg,' '); } print("\n"); shmctlCompliance
SyntaxCategory list operator (System V) Arguments id, cmd, arg Return Value value DefinitionThis function is equivalent to the UNIX shmctl() function and performs shared memory control operations. shmgetCompliance
SyntaxCategory list operator (System V) Arguments key.size, flags Return Value value DefinitionThis function is equivalent to the UNIX shmget() function and returns shared memory segment ID. shmreadCompliance
SyntaxCategory list operator (System V) Arguments id, var. pos, size Return Value value DefinitionThis function is equivalent to the UNIX shmread() function and reads from the shared memory segment ID. shmwriteCompliance
SyntaxCategory list operator (System V) Arguments id, string, pos, size Return Value value DefinitionThis function is equivalent to the UNIX shmwrite() function and writes to the shared memory segment ID. shutdownCompliance
SyntaxCategory list operator (socket) Arguments socket, how Return Value 1 (true) '' (false) DefinitionThis function is equivalent to the UNIX shutdown() function and shuts down a socket. sinCompliance
SyntaxCategory named unary operator (numeric) Arguments expression Arguments none Return Value numeric DefinitionThis function returns the sine of the expression in radians. If there is no explicit argument, $_ is used. Exampleprint("sin() ",sin(4), "\n"); sleepCompliance
SyntaxCategory named unary operator (process) Arguments expression Arguments none Return Value numeric DefinitionThis function causes the current process to sleep for the number of seconds specified in expression (if none is specified, it sleeps forever but may be woken up by a signal if this has been programmed). Exampleprint("sleep() ",sleep(5),"\n"); socketCompliance
SyntaxCategory list operator (socket) Arguments socket, domain, type, protocol Return Value value DefinitionThis function is equivalent to the UNIX socket() system call and opens a specified type of socket and attaches it to a file handle. socketpairCompliance
SyntaxCategory list operator (socket) Arguments socket1, socket2, domain, type, protocol Return Value value DefinitionThis function is equivalent to the UNIX socketpair() system call and creates a pair of sockets, which are unnamed, in the specified domain. sortCompliance
SyntaxCategory list operator (list) Arguments subname list Arguments block list Arguments list Return Value list DefinitionThis function sorts the list specified and returns the sorted list. The sort method can be specified with the optional subroutine or block argument. A subroutine may be specified that takes two arguments (passed as global package variables, $a $b) and returns TRUE if the first is less than or equal to the second by any criteria used. Similarly, a block can be specified (effectively an anonymous subroutine) to perform this function. The default sort order is based on the standard string comparison order. Example@a = ("z","w","r","i","b","a"); print("sort() ",sort(@a),"\n"); spliceCompliance
SyntaxCategory list operator (array) Arguments array, offset, length, list Arguments array, offset, length Arguments array, offset Return Value list DefinitionThis function removes the elements specified by offset and length from the array and replaces them with the elements in the list supplied as the last argument. A list of those elements removed is returned. If no length is specified, all the items from offset to the end of the array are removed. Example@a = ("a","e","i","o","u"); print("splice() ",splice(@a,0,3,"A","E","I"),"\n"); splitCompliance
SyntaxCategory list operator (pattern) Arguments /pattern/,expression,limit Arguments /pattern/,expression Arguments /pattern/ Arguments none Return Value list DefinitionThis function manipulates a string, splitting the string denoted by the expression (or the $_ if none is specified) into an array of strings based on some separator string specified by the pattern (if the pattern has no specified whitespace as the default). An optional limit restricts the number of elements returned. A negative limit has no effect. If not in a list context, the number of elements found is returned. In an scalar context, it returns the number of elements and puts the resulting array into the @_ array (the use of the @_ as the result is depreciated). Examplesprint("spilt() ",split(/:/,"1:2:3:4:5"),"\n"); sprintfCompliance
SyntaxCategory list operator (string) Arguments format, list Return Value string DefinitionThis is equivalent to the C sprintf() call. The format is a string with special metacharacters to specify how may values/variables follow and how to represent each of these in the resulting string. This enables the explicit formatting of floating point and integer numbers (also enabling binary, hexidecimal, and octal formats). Exampleprint("strintf() ",sprintf("%0d \n",9),"\n"); sqrtCompliance
SyntaxCategory named unary operator (numeric) Arguments expression Return Value numeric DefinitionThis function returns the result of evaluating the expression and finding its square root. Exampleprint("sqrt() ",sqrt(4),"\n"); srandCompliance
SyntaxCategory named unary operator (numeric) Arguments expression Arguments none Return Value 1 (true) '' (false) DefinitionThis function sets the seed used by the pseudorandom number generation algorithm when generating rand() numbers. In order to randomize the possible sequences, the seed should be set to a different value each time the script is called. The default behavior, when no expression is supplied, is to use the result of a call to time(). This is not a secure method of randomizing for scripts that need to be secure because it is possible to predict what sequence the script will return. Note that, when using a set of pseudorandom data generated using rand(), it is possible to generate exactly the same data repeatedly (without having to save the entire sequence) simply by stetting and saving the seed. Restoring the seed and calling rand() will then produce the same sequence again. Examplesrand(26); print("rand() ",rand(),", "); srand(26); print(rand()," (should produce the same \"random\" number twice) \n"); statCompliance
SyntaxCategory list operator (files) Arguments handle Arguments expression Arguments none Return Value list DefinitionThis function returns the file statistics of the file pointed to by the file handle (or a file handle produced by evaluating the expression). Note that, like the file test operators, stat() can take a special argument underscore; this means that the test is carried out on the same file handle as the last file test, stat(), or lstat() call. Example($device,$inode,$mode,$nlink,$uid,$gid,$rdev,$size,$atime, $mtime,$ctime,$blksize,$blocks) = stat("/etc/ passwd"); print("stat() $device, $inode, $ctime \n"); studyCompliance
SyntaxCategory named unary operator (pattern) Arguments scalar Arguments none Return Value 1 (true) '' (false) DefinitionWhen many pattern match operations are being performed on the same string, the efficiency of these patterns can be improved with the study() function. If no string is specified, the $_ is studied by default. The call sets up internal lookup tables based on the string studied so that pattern matching operations can use this information to process the pattern match more quickly. Only one string at a time can be studied (subsequent calls effectively "unstudy" any previous study() removing the lookup tables). The function study() is often used in a loop processing lines of a text file where each line is studied before being processed with various pattern matches. subCompliance
SyntaxCategory (flow) Arguments name block Arguments name Arguments name Return Value value DefinitionThis is the syntax for a subroutine declaration. The full form defines a subroutine with the name and associates this with the statements in block. When evoked, it will return the result of the last statement executed in the block (often a return() statement). If no name is supplied, it is an anonymous subroutine (certain functions such as sort() allow anonymous subroutines as arguments). With only a name as an argument, the statement is a forward reference to a subroutine, which is fully declared later in the script. substrCompliance
SyntaxCategory list operator (string) Arguments expression, offset, length Arguments expression, offset Return Value string DefinitionThis function returns a substring of a string specified by expression. The substring starts at the specified offset and has the specified length. If the offset is negative, it starts from the right side of the string instead of the left side. If the length is negative, it means to trim the string by that number of characters. Exampleprint("substr() ",substring("okay",0,2),"\n"); symlinkCompliance
SyntaxCategory list operator ((files) Arguments oldfile, newfile Return Value 1 or 0 DefinitionThis function creates a symbolic link from the existing file specified by oldfile to the specified newfile and returns 1 on success and 0 on failure. If symbolic links are not supported by the operating system, this will return a fatal error. Exampleprint("symlink() ",symlink("/usr/local","/tmp/symlinktousrlocal"),"\n"); syscallCompliance
SyntaxCategory list operator (i/o) Arguments list Return Value varies DefinitionThis mechanism allows Perl to call corresponding UNIX C system calls directly. It relies on the existence of the set of Perl header files Syscall.ph which declares all of these calls. The script h2ph that is normally executed when Perl is installed, sets up the Syscall.ph files. Each call has the same name as the equivalent UNIX system call with the SYS_ prefix. As these calls actually pass control to the relevant C system function. Care must be taken with passing parameters. The fisrt element in the list used as an argument to syscall() itself, is the name corresponding to the UNIX system call (that is, with the SYS_ prefix). The next elements in the list are interpreted as parameters to this call. Numeric values are passed as the C type int. String values are passed as pointers to arrays. The length of these strings must be able to cope with any value assigned to that parameter in the call. Examplerequire "syscall.ph"; print("syscall() ",syscall(&SYS_getpid)," equivalent to $PID\n"); sysopenCompliance
SyntaxCategory list operator (i/o) Arguments handle, name, mode, permissions Arguments handle, name, mode Return Value 1 (true) '' (false) DefinitionThis function calls the UNIX C open() function directly from the Perl script, which opens a file for reading or writing. sysreadCompliance
SyntaxCategory list operator (i/o) Arguments handle, scalar, length, offset Arguments handle, scalar, length Return Value 1 (true) '' (false) DefinitionThis function calls the UNIX C read() function directly from the Perl script, which reads a line from the standard input source. systemCompliance
SyntaxCategory list operator (process) Arguments list Return Value status Definition
This call executes the specified list as an operating system call.
The process to execute this command is forked and the script waits
for the child process to return. The return value is the exit
status of the child process.
Exampleprint("system() ",system("ls -F /var > /tmp/t.tmp"),"\n"); syswriteCompliance
SyntaxCategory list operator (i/o) Arguments handle, scalar, length, offset Arguments handle, scalar, length Return Value 1 (true) '' (false) DefinitionThis function calls the UNIX C write() function directly from the Perl script, which is an interactive write to another user process. tellCompliance
SyntaxCategory named unary operator (i/o) Arguments expression Arguments none Return Value position DefinitionThis function returns the current position in the file specified by the expression (which should evaluate to a file handle). If no handle is specified, the last file accessed is used. This value can be used by seek() to return to this position if appropriate. Exampleprint("tell() ",tell(STDOUT),"\n"); telldirCompliance
SyntaxCategory named unary operator (i/o) Arguments dirhandle Return Value position DefinitionThis function returns the current position in the directory handle specified. This value can be used by seekdir() to return to this position if appropriate. Exampleopendir(DIR,"/tmp"); readdir(DIR); print("telldir() ",telldir(DIR),"\n"); tieCompliance
SyntaxCategory list operator (class) Arguments variable, classname, list Return Value object DefinitionThis function binds a variable to a package class. It creates an instance of this class by running the new() method associated with that class. Any parameters for the new() method may be specified in the list. The behavior depends on the way the package class is written and on the type of variable. Most common are package classes written to support associative arrays. In particular, package classes exist to bind associative arrays to various databases. The tie() mechanism hides all the complexities of implemention behind a simple interface so that, for example, the records in a database can be accessed by looking at the associative array bound to the database though an appropriate package class. The example here uses the Configure.pm module. This module gives access to information about the machine on which Perl was installed. It is possible to bind an associative array to this class and examine this to find out the value of any of the configuration parameters. Exampleuse Configure; $return = tie %c, Configure; print("tie() returned \"$return\" and ", "a sample value is $c{installbin}\n"); tiedCompliance
SyntaxCategory named unary operator Arguments variable Return Value object DefinitionThis function was first implemented in Perl 5.002 and returns a reference to the object that the variable is an instance of. This is the same as is returned by the original call to tie() when it is bound. timeCompliance
SyntaxCategory (time) Arguments none Return Value time DefinitionThis function returns the time, in seconds, since 1 January 1970. The format can be converted into more useful parts using gmtime() or localtime(). timesCompliance
SyntaxCategory (process) Arguments none Return Value list DefinitionThis function returns a list of four elements representing the time, in seconds, used. The four elements represent the system time and the user time used by the current process and child processes. Example($usertime,$systemtime,$childsystem,$childuser) = times(); print("times() $usertime $systemtime $childsystem $childuser\n"); tr///Compliance
SyntaxCategory (string) Arguments tr/searchlist/replacelist/<options> Return Value numeric DefinitionThis function translates all occurrences of items in the search list with the equivalent items in the replacement list. The string searched is the default search string bound by =~ or !=, or if no string is bound to the pattern match, the $_ string is used. The return value is the number of characters translated or deleted.
The valid options are
The searchlist and the replacelist may contain the character to indicate a range of characters. Examples
|
tr/AEIOU/aeiou/ | # Make all vowels lowercase |
tr/[A-M]/[a-m]/ | # Make first half of alphabet lowercase |
tr/aeiou/ /c | # Replace all non-vowels with space |
tr/aeiou/AEIOU/d | # Make all vowels uppercase and # remove all
other characters |
tr/aeiou/-/s | # Replace all vowels with -, # but only one -
for adjacent vowels |
Category list operator (i/o) Arguments handle, length Arguments expression, length Return Value 1 (true) '' (false)
This function truncates the file referenced by the file handle to length. An expression can be used that evaluates to the file handle if the operating system does not implement this feature.
Category named unary operator (string) Arguments expression Return Value string
This function returns an uppercase version of the specified
expression.
print("uc() ",uc("This is All Caps"), "\n");
Category named unary operator (string) Arguments expression Return Value string
This function returns a string
with the first character of the
expression in uppercase.
print("ucfirst() ",ucfirst("this is Capitalized"), "\n");
Category named unary operator (files) Arguments newumask Arguments none Return Value oldumask
This function sets the file mask using the specified newumask. It returns the oldumask so that it can be stored and restored later if required. If called without any arguments, it returns the current umask. This is the mechanism UNIX uses to modify the permissions of any files created.
print("umask() The current umask is: ",umask,"\n");
Category named unary operator (misc) Arguments expression Arguments none Return Value value
This function undefines the value of the expression. The expression may be a scalar value, and array, or a subroutine (specified with an & prefix). When called without an expression, this function returns an undefined value.
Category list operator (files) Arguments list Return Value numeric
This function deletes the files in the list and returns the number of files deleted.
system("touch /tmp/t.tst"); print("unlink() ",unlink("/tmp/t.tst"),"\n");
Category list operator (data) Arguments template, expression Return Value list
This function unpacks data that are packed with pack(). It uses the same template mechanism to specify the format of the data in the packed string. In a scalar context, the first value in the list is returned.
Category list operator (array) Arguments array, list Return Value numeric
This function prepends the list to the front of the specified array and returns the new number of elements in array.
@a = (a, b, c); $ret = unshift(@a, 1, 2, 3); print("unshift() Array has $ret elements:",@a,"\n");
Category named unary operator (class) Arguments variable Return Value 1 (true) '' (false)
This function undoes the binding between a variable and a package class that was created using tie().
Category list operator (module) Arguments module, list Return Value N/A
This function imports the specified module into the current block. The import() method defined for the package class represented by the module is evaluated. The specified list is passed as optional arguments to this import() method. If you do not specify a list argument, then the default methods for that module will be those imported. You can specify the empty list() in order to avoid adding any items to the local namespace.
use English;
Note that this is the mechanism for implementing compiler directives known as pragmas. You can, for example, force all aritmateic to be interger based by
use integer;
And then this can be turned off again with
no integer;
Category list operator (files) Arguments list Return Value numeric
This function sets the access and modification time of all the files in the list to the time specified in the first two items in the list. The time must be in the numeric format (that is, seconds since 1 January 1970) as returned by the time() function.
$time = now; print("utime() ",utime($time,$time,"/tmp/t.tst"),"\n");
Category named unary operator (hash) Arguments variable Return Value list
This function returns the array comprising all the values in the associate array specified. In a scalar context, it returns the number of values in the array.
%a = (1, "one", 2, "two", 3, "three"); print("values() ",values(%a),"\n);
Category list operator (fixed) Arguments expression, offset, bits Return Value value
This function uses the string specified by expression as a vector of unsigned integers. The return value is the value of the bitfield specified by offset. The specified bits is the number of bits that are reserved for each entry in the bit vector. This must be a power of 2 from 1 to 32. Note that the offset is the marker for the end of the vector, and it counts back the number of bits specified to find the start.
Vectors can be manipulated with the logical bitwise operators
|, &,
and ^.
$vec = ''; vec($vec,3,4) = 1; # bits 0 to 3 vec($vec,7,4) = 10; # bits 4 to 7 vec($vec,11,4) = 3; # bits 8 to 11 vec($vec,15,4) = 15; # bits 12 to 15 # As there are 4 bits per number this can be decoded by # unpack() as a hex number print("vec() Has a created a string of nybbles, in hex: ", unpack("h*",$vec),"\n");
Category (process) Arguments none Return Value pid
This function waits for a child process to exit. It returns the process ID (pid) of the terminated process and -1 if there are no child processes.
Category list operator (process) Arguments pid, flags Return Value pid
This function waits for a specified child process to exit and returns pid of the terminated process and -1 if there is no child process matching the pid specified. The flags can be set to various values that are equivalent to the waitpid() UNIX system call (if the operating system supports this), a flags value of 0 should work on all operating systems supporting processes.
Category (flow) Arguments none Return Value 1 (true) '' (false)
This function returns 1 if the current context is an array context; otherwise, it returns ''. This construct is most often used to return two alternatives from a subroutine, depending on the calling context.
return wantarray ? (8, 4, 33) : 3;
Category list operator (i/o) Arguments list Return Value 1 (true) '' (false)
This function prints the supplied list to STDERR, like die(). If there is no newline in the list, warn() appends the text at line <line number>\n to the message. However, the script will continue after a warn().
Category list operator (i/o) Arguments expression Arguments handle Arguments none
This function writes a formatted record to the file handle (or the file handle that the expression evaluates to). If no file handle is specified, the default is STDOUT; this can be altered using select() if necessary.
A format for use by that file handle must have been declared using the format() function. This defaults to the name of the file handle being used, but other format names can be associated with the current write() operation using the $FORMAT_NAME ($~) special variable.
Category (string) Arguments y/searchlist/replacelist/<options> Return Value numeric
The y/// operator is a synonym for the translation operator tr///.