appendix A

Perl 5 Function and Variable Reference


This appendix presents a brief alphabetic synopsis of all available Perl functions to enable you to quickly look up the functions' syntax. This appendix is not intended to provide a complete, exhaustive reference. For a complete documentation set on Perl 5, you can visit the CPAN site described in the following note.

Note
You can obtain the complete reference manual for Perl from the CPAN Web sites. The most comprehensive set is the 950KB zipped file available at the following URL:
www.perl.com/CPAN/doc/manual/text/PerlDoc-5.002b1g-txt.tar.gz
Once unzipped and untarred, the archive expands to several reference documents. These online documents will provide a far more comprehensive, up-to-date reference material on Perl than is provided in this appendix.

Here are a few points to note when using this appendix:

-X [FILEHANDLE or Expression]

The -X command is a unary file test operator. X can take one of the following values:

-A
Same for access time.
-B
File is a binary file (opposite of -T).
-b
File is a block special file.
-c
File is a character special file.
-C
Same for inode change time.
-d
File is a directory.
-e
File exists.
-f
File is a plain file.
-g
File has setgid bit set.
-k
File has sticky bit set.
-l
File is a symbolic link.
-M
Age of file in days when script started.
-o
File is owned by effective uid.
-O
File is owned by real uid.
-p
File is a named pipe (FIFO).
-r
File is readable by effective uid/gid.
-R
File is readable by real uid/gid.
-s
File has non-zero size (returns size).
-S
File is a socket.
-t
File handle is opened to a tty.
-T
File is a text file.
-u
File has setuid bit set.
-w
File is writable by effective uid/gid.
-W
File is writable by real uid/gid.
-x
File is executable by effective uid/gid.
-X
File is executable by real uid/gid.
-z
File has zero byte size.

The -X operator takes one argument: a filename or a file handle. Then it applies a test with the associated file for what's requested. It uses $_ if no argument is given. The exception to this rule is the -t test, which defaults to using STDIN. The function returns 1 if the tested condition is true; otherwise, it returns false. The precedence for this operator is the same as any other named unary operator. The arguments into this function may be parenthesized like any other unary operator.

The permission operators (-r, -R, -w , -W, -x, and -X ) test the umask file permissions and those of the calling program's uids and gids. Other reasons why you can't actually read, write, or execute the file are ignored. When tested while a program is running as root, the read/write flags will always return 1 as the test. The values from the -x and -X return 1 only if any execute bit is set. It's probably better to use the stat() function instead to figure out the mode of the file.

The -T and -B switches determine the type of file by looking at the first few blocks of the file. If there are non-ASCII characters in there, the file is assumed to be binary. Control codes generally have the highest bit set, which is what Perl looks for. Also, any file containing null in the first block is considered a binary file.

If -T or -B is used on a file handle, the current input buffer is examined rather than the first block. Both -T and -B return TRUE on a null file or from a file pointer at EOF when testing a file handle. To be able to perform a -T or -B test on a file, you have to be able to read it. To test for readability, use the -f option along with the -T or -B flag: -f $file && -T $file. Like the stat() operator, the special handle referred by the underscore (_) is the last file handle used. This shortcut does not work with -t.

abs value

The absolute value of its argument. Non-numeric arguments return a value of 0.

accept newSocket, oldSocket

This call is used to accept an incoming packet. The return value is the packed address if successful, or FALSE if not successful. The underlying call is the same as the accept() system call in UNIX. See Chapter 12, "Using Sockets."

alarm seconds

Sets up a timer to send the SIGALRM signal to a process after the approximate number of seconds in the argument have passed. Each call to alarm resets any previous timer. A value of 0 for the timer disables any previous timer. The returned value is the number of seconds on the previous timer. Don't use the sleep() call with the alarm call in the same code block because they share the same internal Perl variables in two different ways.

atan2 Y,X

Returns the arctangent of Y/X. The returned value is guaranteed to be in the range [-PI , PI].

bind socket,name

Used to bind a network address to a socket. Returns TRUE on success or FALSE on any failure. The name must be a packed address of the appropriate type for the socket. See Chapter 12.

binmode FILEHANDLE

Forces binary mode on the file specified by the FILEHANDLE handle. Those files not in binary mode will have the CR, LF line termination translated to LF on input, and LF to CR,LF on output, in non-UNIX systems. The FILEHANDLE may be the value of an expression.

bless REFEREncE[,CLASS]

The bless function forces the REFEREncE referenced object to be an object of the type ClassName. If no ClassName is specified, the current class name is used. The REFEREncE value is returned by this function. The bless function is usually the last item called in a constructor for an object.

Note that the two-argument version is the preferred way of calling the bless function. The one-argument function might cause the wrong class to be bless-ed if the class is inherited by a derived class.

chdir newDir

Sets the current working directory to the value in newDir. The function returns TRUE if the change was okay, FALSE if not.

chmod mode listOfFileNames

Works like the chmod command in UNIX. The first argument is an octal number of the bits or the UNIX mode (for example +w) to set in the list of filenames that follow. Returns the number of files whose mode was successfully changed.

chomp variable
chomp list
chomp

The chomp function removes the ending part of a line if the terminating characters are of the same value as the $/ variable. The function returns the number of characters removed. If variable is omitted, the $_ variable is chomp-ed. If you set $/ to "", all blank lines are removed. If you chomp a list, each element is chomp-ed, and the total number of characters removed is returned. Like chop, the chomp function can be used on the results of expressions:

chomp($users = `who`);
             chomp($answer = <STDIN>);

chop variable
chop list
chop

Removes the last character from a string. If no variable or list is specified, chop uses the $_ variable. If the input to chop is a list, it removes the last item in the list. If the input to chop is a string, it removes the last character in the string. The last item chop-ed is the return value.

chown uid gid listOfiles

Change the owner with uid and group with gid of a list of files. The function returns the number of files successfully changed. Caller must have permissions to write on the files you are modifying. Both uid and gid must be numbers or evaluate to numbers.

chr number

Returns the character for the underlying operating system given its index in a character set.

chroot rootDir

Makes the value in rootDir the root directory for all relative pathnames used in the application. The current working directory is not changed. chroot uses $_ if no argument is specified. This only works if you are running this script as superuser.

close

Closes the file, socket, or pipe associated with the file handle. Returns TRUE if all the buffers are flushed and the system call to close the file, pipe, or socket succeeds. Re-opening a file with the open() file closes the file automatically. The $. variable for line counts is reset to zero when a file is closed, but not when the file is re-opened. Closing a pipe causes the calling process to wait for the process executing on the pipe to complete. Closing a pipe explicitly also puts the status value of the current command in a pipe into $?.

closedir

This function closes a directory opened by opendir().

connect SOCKET,name

Connects using sockets to a remote socket. Returns TRUE if it succeeded, FALSE otherwise. The name should be a packed address of the appropriate type for the socket. See Chapter 12.

continue code block continue

Processes the next item in a loop. Execute the code block before proceeding to the top of the loop.

cos Expression

Returns the cosine of Expression whose value must be expressed in radians. Use the $_ if no variable is specified.

crypt

Uses a function similar to the UNIX crypt() function to encrypt the passed text using the value in salt.

dbmclose hash

Breaks the binding between a DBM file and an associative array.

dbmopen hashName,DBname,mode

This call binds a Perl supported DB file to an associative array. DBname is the name of the database without any extensions. The mode is the permissions with which to open the database. The default database is sdbm. If you don't have write access to the DB file, all your assignments will not be written to disk and instead will trigger a trap instruction.

defined Expression

Returns true if the Expression is assigned a value and returns false if the value of Expression is not defined (undef). If applied to a hash array element, it tells you whether the key exists for the hash.

delete Expression

Deletes the specified Expression from a hash. The deleted value is returned. Note that any deletions on the %ENV array modify the environment variables for a program. Deleting a hash entry that's mapped to a disk file with tie() will delete the entry from the disk file. Deleting from a tied hash always returns undef.

die Message

The die() function is the de facto bailout function for a Perl script. The most common use is to include the $! variable to provide some error message of why it died. In a script, die() prints the Message to the standard error and exits with the value in $!. If $! is zero, the value of ($?>>8) is returned. If the value of $? is zero, a value of 255 is returned. Inside an eval() block, the Message is placed into the $@ variable and the eval() block is terminated with 'undef'.

If the message does not end in a newline, the line number of the script and the line number of the input is also printed along with a newline.

do code block

Returns the value of the last command in the sequence of commands in the code block. The do command executes the code block at least once.

do Expression

Uses the value of Expression as a filename and executes the contents of the file as a Perl script. Its use is the same as eval `cat filename.pl`;.

dump Label

Forces a core dump for later use with the undump command. When the core is undump-ed, the new code jumps to the location at Label with the environment restored as much as possible.

each HASH

This function returns a two-item list-the first item is the key and the second is the value at the key in a hash. The each function can be used in an iterative loop because it returns null at the end of the array. Calling each() after getting a null value causes it to start over from the first {key, value} pair in the hash. Do not add elements to an array while you're iterating over it. There is a single iterator for each associative array that is shared by all each(), keys(), and values() function calls in a program.

endpwent
endgrent
endhostent
endnetent
endprotoent
endservent

These functions perform the same function as the underlying system call.

eof FILEHANDLE
eof ()
eof

This function returns true if the next read on FILEHANDLE returns end of file or if FILEHANDLE is not open. If no FILEHANDLE is specified, the last file handle used in a statement is assumed. The FILEHANDLE may be an expression whose value gives the real file handle. This function should not be used for reading from the console. If used in a while (<>) loop, the eof() call is valid for each file being read.

eval
eval Expression
eval code block

Evaluates the expression passed to it just like a Perl program and returns the value of the last expression evaluated. A return statement may be used in an eval() statement. The call returns an undefined value if there is a runtime error or if the die() call is made. The $@ variable is set to the error message. If there was no error, $@ is set to null. The eval() call uses $_ if no expression is given. The final semicolon in a code block is not necessary.

exec command [args ... ]

The exec() function executes a system command and does not return. This call is generally made after a fork() call. The arguments to the exec command include the command to execute in the first argument, followed by any arguments to that command.

exists Expression

Checks if a key exists in a hash. Returns true if the key does exist, and null if it does not.

exit Expression

Exits with the value from the Expression evaluation. If no Expression is given, it exits with a value of 0.

exp Expression

Returns the natural logarithm base to the power of Expression. Uses $_ if no Expression is given.

fcntl FILEHANDLE,function,scalar

Implements the fcntl(2) function and requires the Fcntl module.

fileno FILEHANDLE

Returns the file descriptor id for a file handle and is used with the select() call. The FILEHANDLE may be an expression whose value would be used as the name of the file handle.

flock FILEHANDLE,operation

Calls the system function flock(2) on FILEHANDLE. Returns true on success and false on failure. The flock function locks files, not records within files-but it's portable across platforms, especially if the locked files exist across the network.

fork

This is a fork(2) system call. Upon return, the parent process gets the child pid, and the child process gets a 0. The parent process gets undef in case of errors. It's a good idea to set $| to 1 before a fork or to call the autoflush(FILEHANDLE) function to flush any pending output before the fork call because buffers are not automatically flushed by fork().

format

The format command. See Chapter 19, "Generating Reports."

getc
getc FILEHANDLE

Does a getc() I/O call to get the next character from the input file specified in FILEHANDLE. It returns null if at end of file. If no FILEHANDLE is specified, getc uses STDIN for input.

getgrgid GID
getpwuid UID

Gets the password or group file entry from the user or group ID. Each function performs the same function as the underlying system call.

gethostbyname name
getnetbyname name
getprotobyname name
getservbyname name,protocol
gethostbyaddr addr,addressType
getnetbyaddr addr,addressType

These functions perform the same function as the underlying system call to return the net structure. See networks(5) in the UNIX manuals.

getlogin

Gets the current login name from /etc/utmp, if any. It's better to use getpwuid($<).

getpeernam socket

Gets the packed sockaddr structure with the socket address of the remote computer at the end of a socket connection.

getpgrp pid

Gets the current process group for the specified pid. You can use 0 or null for specifying the current process.

This function may raise a fatal exception if the underlying system call is not supported.

getppid

Gets the process ID of the parent process.

getpriority processID
getpriority UID

Gets the current priority for a process, a process group, or a user using the getpriority(2) system call. This function may raise a fatal exception if the underlying system call is not supported.

getprotobynumber number

Returns the protocol by number.

getpwent
getgrent
gethostent
getnetent
getprotoent
getservent

These functions perform the same function as the underlying system call.

getpwnam name
getgrnam name

Gets the password or group file entry given a name. This function performs the same function as the underlying system call.

getservbyport port, proto

This function performs the same function as the underlying system call. The port is the port number to use for the given protocol in proto. Check out the file /usr/include/net.h for these values.

getsockname SOCKETHANDLE

Gets the packed sockaddr structure with the address of the local end of a socket connection.

getsockopt SOCKETHANDLE,level,optname

Gets the socket option requested, or is undefined if there is an error. This function performs the same function as the underlying system call.

glob Expression

Expands the value of Expression to filenames just like a shell operation.

gmtime Expression

Converts the time value returned by the time() function to a nine-element array adjusted for the standard Greenwich time zone. All returned array elements are numeric and come straight out of a struct tm defined in /usr/include/time.h.

goto LABEL
goto Expression
goto &name

The goto LABEL form jumps to the statement labeled with LABEL. You cannot jump into a subroutine or within a loop. The Expression is used for computed GOTOs. GOTO &name substitutes a call to the named subroutine for the currently running subroutine. The code returns back from the newly referenced subroutine.

grep Codeblock @list
grep Expression, @list

Runs grep on the Codeblock or Expression for each element of @list by setting $_ to each element in the @list. The return value is a list of all the elements that matched the grep expression. For example, @freds = grep(/fred/, @users); gets all the strings with the word fred in @users.

hex Expression

Evaluates Expression as a hex string and returns the corresponding decimal number.

import moduleName

Used to import other modules into a program.

index string,substr,[position]

Gets the position of the first occurrence of substr in str at or after the optional parameter, position. If position is omitted, a search is started from the beginning of the string. The return value is indexed from 0 or h, the value in the $[ variable. Returns -1 or ($[ - 1) if no substr was found.

int Expression

Parses the Expression to return the integer portion. If Expression is omitted, $_ is used to parse for integer.

ioctl FILEHANDLE,function,scalar

Implements the ioctl(2) function. See Chapter 15, "Direct Access to System Facilities."

join Expression,list
join Expression,@array

Creates a string from elements of a list or array. Uses the value of Expression as the separator of items in the string.

keys %hash

Returns an array whose members are all the keys of the named hash. For example, you can get the environment variables with @keys = keys %ENV;.

kill Signal @List-of-PIDs

Sends a signal to the list of processes whose process IDs (PID) are listed in the @List-of-PIDs. The first element is the signal to send. The function returns the number of processes successfully signaled.

last [LABEL]

This function breaks out of a loop in which it's used. Usually, it only breaks out of the inner-most loop. If a LABEL is specified, the code jumps to the statement after the end of the current loop.

lc String

Returns a lowercase version of String.

lcfirst String

Returns the value of String with the first character lowercased.

length [String]

Returns the length in characters of the String. If String is not provided, $_ is used.

link Oldfile,Newfile

Creates a link from old file to a new filename; returns true on success and false on failure.

listen Socket,Queuesize

Works like the listen system call. Returns true on success, false otherwise.

local variable[,variable[,variable ... ]]

Creates local variables in a subroutine or other code block. A local variable is visible to other code blocks nested within the scope of where a local variable is declared. More than one variable may be declared local on one line. See the my() function. Use parentheses when specifying more than one variable.

localtime Expression

Converts a time value returned by the time() function to a nine-element array with values for the local time zone. The values returned correspond to the tm structure in the file /usr/include/time.h.

log Expression

Returns natural log of Expression. If the Expression is not provided, it returns natural log of $_.

lstat FILEHANDLE
lstat Expression

Works just like the stat() system call. Works on links instead of on a linked file.

map CodeBlock, @list
map Expression, @list

Evaluates the code block or Expression for each element of @ilist by setting $_ to each element in @list. Returns a list of element $_ to each element and returns the list value composed of the results of applying the code block or Expression to @list. For example, the following function returns a list of @names with all lowercase strings:

@allLower = map(lc, @names);

mkdir dirName,permissions

Makes a directory specified by dirName with the permissions specified in the argument. Upon success, it returns 1; otherwise it returns 0.

msgctl QueueID,Action,Arguement

The System V Ipc function msgctl(2) is called here. See Chapter 13, "Message Facilities: The System V Ipc Functions."

msgget KEY,flags

The System V Ipc function msgget(2) is called here. See Chapter 13.

msgrcv QueueID,Var,Sz,Type,flags

The System V Ipc function msgrcv is called here.

msgsnd QueueID,Message,flags

Calls the System V Ipc function msgsnd(2) to send the Message to the message QueueID. The Message must begin with a long integer message type. Returns true if successful and false on error.

my Expression

The my function declares the listed variables to be local to the enclosing block, subroutine, eval, or do/require/use file. Use parentheses when specifying more than one variable. Variables declared as my are not seen by code blocks within the scope of the current block.

next LABEL
next

The next command starts the next iteration of a loop or jump to LABEL. For nested loops, it jumps to the innermost enclosing loop.

no Module[,Module[,Module...]]

The opposite of the use function.

oct Expression

Returns an octal number after parsing Expression. Returns a hex number if the Expression begins with 0x.

open FILEHANDLE[,filename]

Opens the file whose filename is given by filename and associates it with FILEHANDLE. If filename is not specified, the scalar variable of the same name as the FILEHANDLE contains the filename. If the filename begins with >, the file is opened for writing. If the filename begins with >>, the file is opened for appending. If the filename begins with nothing or <, the file is opened for reading. Put + in front of > or < to indicate that you want both read and write access to the file. The +< is for read/write updates, whereas the +> mode overwrites files. If the filename begins with |, the filename is used as a command to which all output to the FILEHANDLE will be piped. If the filename ends with |, the filename is used as a command from which to read input. The - is a synonym for STDIN, and >- is a synonym for STDOUT. Prepending a filename with >& duplicates and opens a new file handle.

Open returns non-zero upon success or the undefined value on error. To do an implicit fork(), use |- or -|. The return value is 0 in the child and the pid of the child in the parent. The STDIN and STDOUT of the child is initially tied to the file handle in the parent.

When working on a pipe, the return value happens to be the pid of the subprocess. Closing any piped file handle causes the parent process to wait for the child to finish and returns the status value in $?.

opendir DIRHANDLE,dirname

Opens a directory named dirname for processing by readdir(), telldir(), seekdir(), rewinddir(), and closedir(). Returns TRUE if successful. DIRHANDLEs have their own name space separate from FILEHANDLEs.

ord [String]

Gets the numeric ASCII value of the first character in String. Uses value of $_ no string is specified.

pack template,@list

Packs a list into a binary structure and returns a string with the structure. The template is a sequence of characters that give the order and type of values.

a
An ASCII string (will be null padded).
A
An ASCII string (will be space padded).
b
A bit string (ascending bit order, like vec()).
B
A bit string (descending bit order).
c
A signed char value.
C
An unsigned char value.
d
A double-precision float in the native format.
f
A single-precision float in the native format.
H
A hex string (high nybble first).
h
A hex string (low nybble first).
i
A signed integer value.
I
An unsigned integer value.
l
A signed long value.
L
An unsigned long value.
N
A long in "network" order.
n
A short in "network" order.
p
A pointer to a null-terminated string.
P
A pointer to a structure (fixed-length string).
s
A signed short value.
S
An unsigned short value.
u
A uuencoded string.
V
A long in "VAX" (little-endian) order.
v
A short in "VAX" (little-endian) order.
x
A null byte.
X
Backs up a byte.

Each letter may optionally be prepended by a number to allow it to be repeated. Use a * for the repeat count to all remaining items in a list. The pack function will use as many values as needed but requires specifications for a, A, b, B, h H, and `P.

package nameSPACE

Used for declaring packages. See Chapter 4, "Introduction to Perl Modules."

pipe readhandle,writehandle

Creates a pair of connected pipes, like the corresponding system call. See Chapter 14, "Signals, Pipes, FIFOs, and Perl."

pop @array

Removes and returns the last value of an array. The array is shortened by one element. Returns undef if @array is empty. Uses the @ARGV array in the main program or the @_ array in subroutines if the @array is not specified.

pos ScalarVariable

Returns the offset of where the last matched search left off for the scalarVariable.

print [FILEHANDLE] LIST

Prints a string or a comma-separated list of strings. Returns true if successful. Writes to FILEHANDLE when specified or uses STDOUT as the default if no other output has been selected.

printf [FILEHANDLE] LIST

Just like the C call to printf.

push @array,@list

Stacks the items in @list onto the end of @array.

q/STRING/
qq/STRING/
qx/STRING/
qw/STRING/

Generalized quotes for strings.

quotemeta String

Returns a copy of String with all the regular expression metacharacters backslashed. See Chapter 7, "Strings and Patterns."

rand [Number]

Returns a random fractional number between 0 and the value of Number. Number must be positive. If Number is not provided, a value between 0 and 1 is returned. Use srand() to seed this function.

read FILEHANDLE,scalar,length[,offset]

Reads length bytes of data into variable scalar from the FILEHANDLE. Returns the number of bytes actually read, or undef in the case of an error. The scalar will be grown or shrunk to the length actually read. The offset to write input in the string to is defaulted to 0 if no offset is explicitly passed as the fourth parameter.

readdir DIRHANDLE

Returns the next directory entry for a directory opened by opendir(). If used in a list context, it returns all the rest of the entries in the directory. For no more entries, it returns an undef value or an empty list if used in list context.

readlink [Expression]

Returns the value of a symbolic link. Crashes the program if symbolic links are not implemented. Upon error, it returns the undefined value and sets $!. Uses $_ for input if Expression is not provided.

recv SOCKET,scalar,len,flags

Receives a message on a socket. See Chapter 12. The data is read into the scalar variable from the specified SOCKET file handle up to len bytes. The flags are as defined in the recvfrom(2) system call.

redo [LABEL]

The redo command restarts a loop block without evaluating the conditional again. The continue block, if any, is not executed. If the LABEL is omitted, the command refers to the innermost enclosing loop.

ref Expression

Returns true if Expression is a reference, or false if it is not. The function returns the name of the package if Expression is a pointer to an object.

rename oldName,newName

Changes the name of the file oldName to newName. Returns 1 for success, 0 otherwise. This function does not work across file system boundaries.

require [Expression]

Uses either Expression or, if no Expression is provided, $_ to determine if some semantics are present. If Expression evaluates to a number, it demands that the current version of Perl ($]) be at least that number. If Expression evaluates to a string, the string is used as the name of the library file to load. Prevents a file from being loaded in twice if the file being loaded in has a 1; statement terminating it. (1; indicates that the file loaded and initialized itself correctly.)

If Expression is a bare word, require assumes a .pm extension for you, to make it easy to load standard modules. This form of loading of modules does not risk altering your name space.

reset [Expression]

Clears values of variables whose names begin with letters in the Expression. More than one letter can be specified using ranges. Uses the ?? special variable if Expression is not specified. The reset function always returns a true value. Here are some examples:

reset 'M';   # reset all M* named variables
reset 'a-z'; # reset lower case variables
reset;       # just reset those listed in ?? searches

Do not use reset 'A-Z'; because this will blow away your environment variables ENV and ARGV!

return arguments

Used to return the list of arguments at the end of a subroutine. A subroutine always returns the result of the last expression in it if no return statement is found.

reverse @list
reverse String

Reverses the order of items in @list. Reverses the order of characters in String.

rewinddir DIRHANDLE

Resets the current position to the start of the directory for use with the readdir() routine on DIRHANDLE.

rindex str,substr[,position]

Gets the position of the last occurrence of substr in str. Starts the search from the end of string unless a position has been specified. If a position is specified, starts the search at the position from the end of the string.

rmdir [DirName]

Removes the directory specified by DirName, but only if the directory is empty. Uses $_ if no DirName is given. Returns 1 on success and 0 otherwise with the error code in $!.

scalar Expression

This operator forces the Expression to be interpreted in a scalar context and returns the value of Expression.

seek FILEHANDLE,position,startingPoint

Set the file pointer for FILEHANDLE just like seek() or fseek() calls in UNIX. The values for startingPoint are 0 to set position from the start of file, 1 to set position relative to the current location in the file, and 2 to set it relative to the end of file. Returns 1 upon success; 0 otherwise.

seekdir DIRHANDLE,position

Moves the current position for the readdir() routine on DIRHANDLE to position, which must be a value returned by telldir().

select [FILEHANDLE]

Sets the default file handle to FILEHANDLE, the currently selected file handle. Returns the current default file handle. All writes and references to output that do not specify a file handle will refer to the FILEHANDLE.

select rbit,wbit,ebit,timeout

The interface to the UNIX select(2) system call. rbit, wbit, and ebit are bitmasks for the select call. The timeout may be 0 if the program wants to wait forever; otherwise, it should be a numeric value in milliseconds. See Chapter 15.

semctl semaphoreID,number,command,argument-list

Works just like the System V Ipc function semctl(2). See Chapter 13 for a complete description.

semget key,nsems,flags

Works just like the System V Ipc function semget(2). See Chapter 13 for a complete description.

semop key,opstring

Works just like the System V Ipc function semop(2). See Chapter 13 for a complete description. The opstring must be a packed array of semop structures. Each semop structure is generated with the instruction pack("sss", $semnum, $semop, $semflag). The number of semaphore operations is implied by the length of opstring. Returns true on success or false otherwise.

send socket,msg,flags[,to]

Sends a message on a socket using the socket(2) system call. See Chapter 12.

sethostent stayopen
setnetent stayopen
setprotoent stayopen
setservent stayopen

These functions perform the same function as the underlying system call. The stayopen value is set to TRUE if the file being read should be kept open, and FALSE otherwise.

setpgrp PID,PGRPID

Sets the current process group for the specified PID. Use a PID of 0 to imply the current process. Works only if the underlying system supports it.

setpriority process,group,user

Sets the current priority for a process, a process group, or a user like the system call to setpriority(2). Works only if the underlying system supports it.

setpwent
setgrent

These functions perform the same function as the underlying system call.

setsockopt socket,level,optionName,optionValue

Sets the socket option named to the value in optionValue. Like the system call to setsocketopt(2). Works only if the underlying system supports it.

shift [@array]shift

Shifts the first value of the @array off and returns it. The size of the @array is reduced by 1. If the @array is empty, it returns undef. Uses @_ in subroutines if @array is not specified.

shmctl shmID,command,argument

Works like the System V Ipc function shmctl(2). If CMD is &Ipc_STAT, the argument must be a variable big enough to hold the returned shmid_ds structure.

shmget shmKey,size,flags

Works just like the System V Ipc function shmget(2). Returns the shared memory segment ID or undef if there is an error.

shmread shmID,VAR,POS,SIZE
shmwrite shmID,STRING,POS,SIZE

Reads or writes the System V shared memory segment shmID by operating at the position POS for SIZE bytes by attaching to the segment, reading or writing to it, and then detaching from the segment. When reading, VAR holds the data read. When writing, up to SIZE bytes in STRING are written. If the length of the string is too short (that is, less than the value in SIZE), null bytes are written to make up the difference. Returns true on success or false otherwise.

shutdown SOCKETHANDLE,how

Shuts down a socket connection by making a system call to shutdown(2).

sin Radians

Returns a double with the sine of the value of Radians. If Radians is omitted, returns sine of $_.

sleep [Seconds]

Makes the program sleep for passed number of seconds. If no arguments are given or if Seconds evaluates to null, the program sleeps forever. Do not mix alarm() and sleep calls in the same program.

socket SOCKETHANDLE,DOMAIN,TYPE,PROTOCOL

Makes a call to open a socket of the specified TYPE in the DOMAIN and uses PROTOCOL. Works like the socket(2) system call.

socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL

Creates two unnamed sockets in the specified DOMAIN of the specified type. Otherwise, works like the socket(2) system call.

sort subroutine @list
sort Code Block @list
sort @list

Sorts the @list and returns the sorted list value. Empty values in arrays are removed. The subroutine or code block are pointers to user-defined functions that take two arguments and return an integer value of 1, 0, or -1. A 1 indicates that the first argument is greater than the second. A 0 indicates that the arguments are equal, and a -1 indicates that the second argument is greater than the first.

splice @array,Offset[,Length[,@list]]

Removes the elements at the Offset and of Length items from the @array and replaces them with the contents of @list. Returns the list of items removed from @array. The @array grows or shrinks as needed. If @list is not provided, nothing is inserted. If Length is not provided, all elements from Offset onward are removed.

split [/Pattern/[,String[,Limit]]]

Returns an array derived from splitting a String into an array of strings of items equal to a number of elements in Limit. If String is not provided, the $_ string is used. The Pattern may be more than one character long. If Pattern is not specified, the function splits on white spaces after removing any leading white spaces. It returns the number of items up to the limit specified and leaves the remainder as one long list. By default, Perl assumes Limit to be one larger than the number of items in the list. A call to split() with no arguments is equivalent to a split(' ', $_ ) call. The Pattern to a split command can be a regular expression or a variable with a regular expression.

sprintf FORMAT,LIST

Returns a string formatted using the printf() syntax.

sqrt Expression

Returns the square root of Expression. Uses $_ if Expression is left out.

srand Expression

Seeds the random number generator for rand() using the Expression as a number.

stat FILEHANDLE
stat FileName

Returns a 13-element array that gives the status information for a file using either the handle FILEHANDLE or the name in FileName. The items in the array are listed in this order: ($device, $inode, $protection, $numberOfhardLinks,$uidOwner, $gidOwner, $deviceType, $totalSize, $blockSize, $blocksUsed, $lastAccessTime, $lastModificationTime, $lastChangeTime). Returns a null list if stat fails. Use stat(_) to return the value from the last stat(FILEHANDLE) call.

sub name

Defines a subroutine for forward referencing.

substr String,Offset,Length
substr String,Offset

Gets a substring from String of up to Length characters and returns it. The first character to extract from is 0. If Length is not provided, everything up to the end of string is returned. If the Offset is negative, the offset starts from the end of the string. If the Length is negative, it leaves that many characters off from the end of the string. The substr() function can be used as an lvalue to patch substrings into String. See Chapter 7 for examples.

symlink oldFile,newFile

Creates a new filename symbolically linked to the old filename. Returns 1 for success or 0 otherwise.

syscall systemCallNumber Arguments

Makes the system call, passing the remaining elements as arguments. Unimplemented system calls, if referenced, produce a fatal error. Strings are passed by reference and numbers as integers.

sysread FILEHANDLE,scalar,length,offset
sysread FILEHANDLE,scalar,length

Reads length bytes of data into variable scalar from the specified FILEHANDLE using the read(2) system call. Returns the number of bytes actually read, or undef in case of an error. The scalar is grown or shrunk to the length actually read. The offset is used to the read data at some other place than at the first byte in scalar.

system program arguments...

Does a fork() to do exactly the same thing as exec but returns to the parent when it's finished. The return value is the exit status of the wait call. To get the actual exit value of the program specified in the system call, divide it by 256.

syswrite FILEHANDLE,scalar,length,offset
syswrite FILEHANDLE,scalar,length

Attempts to write length bytes of data from variable scalar to the specified FILEHANDLE using the system call write(2). Returns the number of bytes actually written, or undef in case of an error. An offset is used to place the read data at the number of offset bytes at the beginning of the string in the scalar.

tell FILEHANDLE
tell

Gets the current file position for FILEHANDLE. If no FILEHANDLE is specified, it uses the file last read.

telldir DIRHANDLE

Returns the current position of the readdir() routines on DIRHANDLE. A value can be used with seekdir() to access a particular location in a directory.

tie variable,classname,LIST

Binds a variable to a class. See the section titled "Using the tie() Operator" in Chapter 6, "Binding Variables to Objects."

time

Returns the number of non-leap seconds since 00:00:00 UTC, January 1, 1970. Used with gmtime() and localtime().

times

Returns a four-item array with the user and system times, in seconds, for this process and the children (if any) of this process.

tr///

The translation operator. See Chapter 7.

truncate FILEHANDLE,LENGTH

Truncates the file opened on FILEHANDLE to the specified length.

uc String

Returns an uppercased copy of String.

ucfirst String

Returns the value of String with the first character uppercased.

umask Expression
umask

Sets the umask for the process and returns the old one. If Expression is not provided, the current umask is returned.

undef Scalar
undef Array
undef Hash
undef Subroutine

Removes any definition of the value of Scalar, hash, array or subroutine by name. This function always returns the undef value.

unlink namedFiles

Deletes the named files. Returns the number of files successfully deleted. The unlink() will not delete directories unless you are superuser and the -U flag is supplied to Perl. Use rmdir instead.

unpack TEMPLATE,Expression

Unpack does the reverse of pack. It takes a structure and expands it into a list of items. TEMPLATE has the same format as in the pack function.

unshift @array,@list

Works the opposite way of shift(). Attaches @list to the front of @array. Returns the new number of elements in the @array.

untie variable

Breaks binding between a variable and a package.

use Module[,Module[,Module ... ]]

Imports all named modules into a program. See Chapter 4 for more information on Perl modules.

utime accessTime Modification Filenames

Modifies the access and modification times on each file in a list of files. Returns the number of files successfully changed.

values %Hash

Returns an array with just the values in random of the named hash. Works like the keys() function except that it returns values.

vec string,offset,bitsToSet

Sets the bits from the values of 0s and 1s in a string. Starts setting bits at the offset. Returns the value of the bitfield specified. The bitsToSet to set must be a power of 2 from 1 to 32. It's an easier way of setting bits than using logical operators.

Wait

Waits for a child process to terminate and returns the pid of the deceased process, or -1 if there are no child processes. The status is returned in $?.

waitpid PID,flags

Waits for a particular child process to die and returns the PID of the dead process. It returns -1 if there is no such child process. The status is returned in $?.

wantarray

Returns true if the currently executing subroutine is looking for list value. Returns false if the subroutine is looking for a scalar.

warn Message

Prints an error message on STDERR just like die() but doesn't exit.

write FILEHANDLE
write Expression
write

Writes a formatted record to the specified file using the format associated with that file. See Chapter 19.

y///

The translation operator (just like the tr operator).