Appendix E

The Perl Quick Reference Manual


CONTENTS

This appendix is a derivation of my knowledge, the Perl man pages, and a GNU Texinfo version developed by Jeff Kellem at composer@Beyond.Dreams.ORG. The copyright information on the modified work is the standard GNU license, which is included at the end of this appendix. You can find the Perl manual online at multiple sites. One of those sites is

http://www.metronet.com/perlinfo/doc/manual/html/

Perl Operators and Their Precedence

Precedence is the order of execution. You can change that order by using parentheses. Parentheses take precedence over any other operator. The innermost set of parentheses takes precedence.

Table E.1 lists the Perl operators in order of their precedence. The first column shows the operators' associativity. Operators on the same line have equal precedence. The table begins with the highest precedence operator and ends with operators with the least precedence.

Table E.1. Operators: their precedence and associativity.

AssociativityOperator
left`('
not associative++ --
right**
right! ~ and unary minus
left=~ !~
left* / % x
left+ - .
left<< >>
not associative-r -w -x and so on
not associativechdir exit eval reset sleep rand umask
not associative< > <= >= lt gt le ge
not associative== != <=> eq ne cmp
left&
left| ^
left&&
left||
not associative..
right?:
right= += \-= *= and so on
left,
not associativeprint printf exec system sort reverse chmod chown kill unlink utime die return

Perl Operators and Their Meanings

Table E.2 lists the Perl operators and their meanings.

Table E.2. Perl operators.

OperatorMeaning
= Assignment
+= -= *= Add, subtract, or multiply the current left-hand value by the value of the right-hand value and assign to the left-hand value
\ Escape
Test?A:B If TEST is True, do A; else do B
.. Range
|| Logical OR
&& Logical AND
^ Bitwise exclusive OR
| Bitwise OR
& Bitwise AND
== != <=> Numeric equals, not equals, and compare, respectively
eq ne cmp String equals, not equals, and compare, respectively
< > Numeric less than, greater than, respectively
<= >= Numeric less than equals, greater than equals, respectively
lt gt String less than, greater than, respectively
le ge String less than equals, greater than equals, respectively
<< >> Bitwise Left Shift, Right Shift, respectively
+ - Add, subtract
. String concatenate
* / % x Multiply, divide, modulo, repeat
=~ Match pattern on right-hand side with data on left-hand side (can be used with substitute operator to modify lvalue)
!~ Same as =~ negated
! NOT
~ Negate operator
** Exponentiation
++ -- Increment, decrement
-x File test

Special Variables

Table E.3 is a list of the names and variables that have special meaning in Perl.

Table E.3. Special variables.

Variable
Meaning
$_
Default input and pattern-searching space.
$.
Current input line number of the last filehandle that was read.
$/
Input record separator-newline by default.
$,
Output field separator for the `print' operator.
$"
Similar to `$,' except that it applies to array values interpolated into a double-quoted string. Default is a space.
$\
Output record separator for the `print' operator.
$#
Output format for printed numbers.
$%
Current page number of the currently selected output channel.
$=
Current page length (printable lines) of the currently selected output channel. Default is 60.
$-
Number of lines left on the page of the currently selected output channel.
$~
Name of the current report format for the currently selected output channel. Default is name of the filehandle.
$^
Name of the current top-of-page format for the currently selected output channel. Default is name of the filehandle with `_TOP' appended.
$|
If set to nonzero, forces a flush after every `write' or `print' on the currently selected output channel. Default is 0.
$$
Process number of the program running this script.
$?
Status returned by the last pipe close, backtick (`) command, or `system' operator.
$&
String matched by the last successful pattern match.
$`
String preceding whatever was matched by the last successful pattern match.
$'
String following whatever was matched by the last successful pattern match.
$+
Last bracket matched by the last search pattern.
$*
Set to 1 to do multiline matching within a string, and set to 0 to tell the Perl interpreter that it can assume that strings contain only a single line for the purpose of optimizing pattern matches. Default is 0.
$0
Name of the file containing the Perl script being executed.
$<digit>
Contains the subpattern from the corresponding set of parentheses in the last pattern matched.
$[
Index of the first element in an array and of the first character in a substring. Default is 0.
$]
String printed when you use `PERL -v'.
$;
Subscript separator for multidimensional array emulation.
$!
If used in a numeric context, yields the current value of errno, with all the usual caveats. If used in a string context, yields the corresponding system error string.
$@
Perl syntax error message from the last `eval' command. If null, the last `eval' parsed and executed correctly.
$<
The real uid of this process.
$>
The effective uid of this process.
$(
The real gid of this process.
$)
The effective gid of this process. Note: `$<', `$>', `$(' and `$)' can only be set on machines that support the corresponding `set[re][ug]id()' routine. `$(' and `$)' can be swapped only on machines supporting `setregid()'.
$:
Current set of characters after which a string may be broken to fill continuation fields (starting with `^') in a format. Default is ` \n-', to break on whitespace or hyphens.
$^D
Current value of the debugging flags.
$^F
Maximum system file descriptor-ordinarily, 2. System file descriptors are passed to subprocesses, whereas higher file descriptors are not. During an open, system file descriptors are preserved even if the open fails. Ordinary file descriptors are closed before the open is attempted.
$^I
Current value of the in-place edit extension. Use `undef' to disable inplace editing.
$^L
Formats output to perform a form feed. Default is `\f'.
$^P
Internal flag cleared by the debugger so that it doesn't debug itself.
$^T
Time at which the script began running, in seconds since the epoch. The values returned by the `-M', `-A', and `-C' file tests are based on this value.
$^W
Current value of the warning switch.
$^X
Name that Perl itself was executed as, from argv[0].
$ARGV
The scalar variable `$ARGV' contains the name of the current file when reading from `<>'.
@ARGV
The array `ARGV' contains the command-line arguments intended for the script.
@Inc
The array `Inc' contains the list of places to look for Perl scripts to be evaluated by the `do EXPR' command or the `require' command. It initially consists of the arguments to any `-I' command-line switches, followed by the default Perl library-probably `/usr/local/lib/PERL', followed by `.', to represent the current directory.
%Inc
The associative array `Inc' contains entries for each filename that has been included via `do' or `require'. The key is the filename you specified, and the value is the location of the file actually found. The `require' command uses this array to determine whether a given file already has been included.
$ENV{expr}
The associative array `ENV' contains the current environment. Setting a value in `ENV' changes the environment for child processes.
$SIG{expr}
The associative array `SIG' sets signal handlers for various signals.

Perl Commands

Table E.4 is an alphabetical list of Perl commands. A brief description of each command is given. When there are multiple syntax formats for a command, the meaning is given only once. If the key word VALUE is used to define the first use of the command and one of the command syntaxes does not include any VALUE, the command operates on $_. When you read VALUE, you can replace that with expression or parameter or variable-whatever you are comfortable with. The key point is that VALUE refers to extra information supplied with the command.

The meanings in this table are purposefully short to keep the table complete and usable as a quick reference of the available Perl commands. Details on most of commands you will need with CGI programming are covered in the main text of this book. You can find further details at

http://www.metronet.com/perlinfo

Table E.4. Perl commands.

CommandFunction
accept(NEWSOCKET,
GENERICSOCKET)
Accepts a new client.
alarm(SECONDS) Generates a sigalarm after the specified SECONDS.
atan2(X,Y) Specifies an arctangent.
bind(SOCKET,NAME) Binds a socket.
binmode(FILEHANDLE)
binmode FILEHANDLE
binmode
Read the file in binary mode.
caller Returns the context of the current subroutine call.
chdir(VALUE)
Chdir VALUE
chdir
Change the working directory to EXP.
chmod(LIST)
chmod LIST
Change the file permissions.
chop(VARIABLE)
chop VARIABLE
chop
Delete the last character.
chown(LIST)
chown LIST
Change the file owner or group.
chroot(FILENAME)
chroot FILENAME
chroot
Change root directory for a command.
close(FILEHANDLE)
close FILEHANDLE
Close the named FILEHANDLE.
closedir(DIRHANDLE)close FILEHANDLE Close the named directory handle.
cconnect(SOCKET,NAME) Makes a connection on a socket.
cos(VALUE)
cos VALUE
cos
Specify the cosine function.
Crypt(PLAINTEXT,SALT) Encrypts PLAINTEXT.
dbmclose(ASSOC_ARRAY)
dbmclose ASSOC_ARRAY
Break the DBM file link with the ASSOC_ARRAY.
dbmopen(ASSOC,DBNAME,MODE) Creates a DBM file link with the ASSOC_ARRAY.
defined(variable)
defined variable
Return True if variable is non-null.
delete $ASSOC{KEY} Deletes the value in the associative array indexed by KEY.
die(LIST)
die LIST
die
Print the value of LIST to STDERR and exit the process.
do BLOCK
do Expression
do SUBROUTINE (LIST)
Return the value of the last command in the sequence of commands indicated by BLOCK.
dump LABEL
dump
Specify that the core dump the process.
each(ASSOCIATIVE_ARRAY)
each ASSOCIATIVE_ARRAY
Return the next key and value to the associative array as a two-element array.

The following functions perform the same system function as defined for the UNIX system on which Perl is operating. These functions are defined by the UNIX operating system on which Perl is running. Perl doesn't actually implement them; it just calls the UNIX system function. So if this function isn't available with your implementation of UNIX, it also isn't available with Perl. To get a complete explanation of these functions, use the UNIX man command (man endpwent, for example).

endpwent
endgrent
endhostent
endnetent
endprotoent
endpwent
endservent

eof(FILEHANDLE)
eof()
eof
Return 1 if the next read on FILEHANDLE will be null or the end of file.
eval(Expression)
eval Expression
eval
Execute the Expression as a Perl program in its own environment.
exec(LIST)
exec LIST
If there is more than one argument in LIST, or if LIST is an array with more than one value, call `execvp()' with the arguments in LIST. If there is only one scalar argument, the argument is checked for shell metacharacters. If there are any, the entire argument is passed to `/bin/sh -c' for parsing. If there are none, the argument is splitinto words and passed directly to `execvp()', which is more efficient.
exit(VALUE)
exit VALUE
Evaluate VALUE and exit.
exp(VALUE)
exp VALUE
exp
Compute e to the power of VALUE.
fcntl(FILEHANDLE,
FUncTION,SCALAR)
Performs the system fcntl function.
fileno(FILEHANDLE)
fileno FILEHANDLE
Return the file descriptor for the FILEHANDLE.
flock(FILEHANDLE,OPERATION) Calls the system flock function. Used for file locking.
Fork Forks a new process.
getc(FILEHANDLE)
getc FILEHANDLE
getc
Get the next character from FILEHANDLE.

The following functions perform the same system function as defined for the UNIX system on which Perl is operating. These functions are defined by the UNIX operating system on which Perl is running. Perl doesn't actually implement them; it just calls the UNIX system function. So if this function isn't available with your implementation of UNIX, it also isn't available with Perl. To get a complete explanation of these functions, use the UNIX man command (man endpwent, for example).

getgrent
getgrgid(GID)
getgrnam(NAME)
gethostbyaddr(ADDR,ADDRTYPE)
gethostbyname(NAME)
gethostent
getlogin
getnetbyaddr(ADDR,ADDRTYPE)
getnetbyname(NAME)
getnetent
getpeername(SOCKET)
getpgrp(PID)
getpgrp PID
getpgrp
getppid
getpriority(WHIch,WHO)
getprotobyname(NAME)
getprotobynumber(NUMBER)
getprotoent
getpwent
getpwnam(NAME)
getpwuid(UID)
getservbyname(NAME,PROTO)
getservbyport(PORT,PROTO)
getservent
getsockname(SOCKET)
getsockopt(SOCKET,LEVEL,OPTNAME)
gmtime(VALUE)
gmtime VALUE
gmtime

goto LABEL Resumes execution at LABEL.
grep(VALUE,LIST) Searches for VALUE in LIST.VALUE.
hex(VALUE)
hex VALUE
hex
Return the hexadecimal value for VALUE.
index(STR,SUBSTR) Returns the position of the first occurrence of SUBSTR in STR at or after POSITION. If POSITION is omitted, starts searching from the beginning of the string. The return value is based at 0 or whatever you've set the `$[' variable to. If the substring is not found, returns one less than the base-ordinarily, -1.
int(VALUE)
int VALUE
int
Return the integer portion of VALUE.
ioctl(FILEHANDLE,
FUncTION,SCALAR)
Uses the system ioctl function.
join(VALUE,LIST)
join(VALUE,ARRAY)
Create a single string from the LIST. Each field of the new string is separated by VALUE.
keys(ASSOC_ARRAY)
keys ASSOC_ARRAY
Return an array of indexes to the associative array.
kill(LIST)
kill LIST
Send a signal to the processes in LIST. The first element of LIST must be the signal to send.
last LABEL
last
Exit the loop associated with LABEL or the innermost loop if LABEL is not supplied.
length(VALUE)
length VALUE
length
Return the number of characters in VALUE. If VALUE is omitted, returns the number of characters `$_'.
link(OLDFILE,NEWFILE) Creates a new filename linked to the old filename.
listen(SOCKET,QUEUESIZE) Listens for a connection on a socket.
local(LIST) Declares the variables defined by LIST to be local in scope to the enclosing block of statements.
localtime(VALUE)
localtime VALUE
localtime
Return the VALUE converted to a nine-element array relative to the local time zone.
log(VALUE)
log VALUE
log
Return the log of VALUE.
lstat(FILEHANDLE)
lstat FILEHANDLE
lstat(VALUE)
lstat SCALARVARIABLE
Get a file's status information by following a symbolic link.
mkdir(FILENAME,MODE) Creates a directory FILENAME with the permission defined by MODE.
next LABEL
next
Resume execution at the start of the loop defined by LABEL.
oct(VALUE)
oct VALUE
oct
Return the octal value of VALUE.
open(FILEHANDLE,VALUE)
open(FILEHANDLE)
open FILEHANDLE
Open the FILEHANDLE using the filename provided by VALUE.
opendir(DIRHANDLE,VALUE)
provided by VALUE
Opens the DIRHANDLE using the directory name .
ord(VALUE)
ord VALUE
ord
Return the numeric ASCII value of the first character of EXP.
pack(TEMPLATE,LIST) Takes an array or list of values and packs it into a binary structure, returning the string containing the structure. The TEMPLATE is a sequence of characters that gives the order and type of values.
pipe(READHANDLE,WRITEHANDLE) Opens paired read and write pipes.
pop(ARRAY)
pop ARRAY
Return the last element of the array and remove it from the array.
print(FILEHANDLE LIST)
print(LIST)
print FILEHANDLE LIST
print LIST
print
Print LIST to FILEHANDLE.
printf(FILEHANDLE LIST)
printf LIST
.printf FILEHANDLE LIST
printf LIST
printf
Print to FILEHANDLE (LIST)
push(ARRAY,LIST) Adds LIST to the end of ARRAY.
rand(VALUE)
rand VALUE
rand
Return a random floating point number between 0 and VALUE. If VALUE is omitted, the range is 0 to 1.
read(FILEHANDLE, SCALAR,LENGTH,OFFSET) read(FILEHANDLE, SCALAR,LENGTH) Attempt to read LENGTH bytes of data into variable SCALAR from the specified FILEHANDLE. Return the number of bytes actually read or `undef' if there was an error. SCALAR is grown or shrunk to the length actually read. An OFFSET may be specified to place the read data at some other place than the beginning of the string.
readdir(DIRHANDLE)
readdir DIRHANDLE
Return the next directory for DIRHANDLE.
readlink(VALUE)
readlink VALUE
readlink
Return the value of a symbolic link.
recv(SOCKET,SCALAR,
LEN,FLAGS)
Reads the number of bytes specified in LEN from SOCKET into SCALAR. Uses the same system flags as defined for the system call.
redo LABEL
redo
Restart the loop block associated with LABEL with evaluating the loop conditional.
rename(OLDNAME,NEWNAME) Renames the file OLDNAME to NEWNAME.
require(VALUE)
require VALUE
require
Add the Perl library defined in VALUE. The subroutines defined in VALUE will be added to the scope of your package.
reset(VALUE)
reset VALUE
reset
Clear the variables in the local scope and reset searches.
return LIST Exits the subroutine, setting the returned value to LIST.
reverse(LIST)
reverse LIST
Reverse the order of LIST.
rewinddir(DIRHANDLE)
rewinddir DIRHANDLE
Reset the DIRHANDLE to the start of the directory.
rindex(STR,SUBSTR) Returns the position of the last occurrence of SUBSTR.
rmdir(DIRNAME)
rmdir DIRNAME
rmdir
Delete the directory associated with DIRNAME.
seek(FILEHANDLE,OFFSET,FROM) Sets the file pointer for FILEHANDLE to the OFFSET starting FROM. FROM may be one of these values:
  0   Beginning of file
  1   Current position
  2   End of file
seekdir(DIRHANDLE,POS) Sets the current position for the `readdir()' routine on DIRHANDLE. POS must be a value returned by `telldir()'.
select(FILEHANDLE) Sets the default output filehandle to FILEHANDLE.
Select Returns the default filehandle.
select(RBITS,WBITS,
EBITS,TIMEOUT)
Calls the system select command.
send(SOCKET,MSG,FLAGS,TO)
send(SOCKET,MSG,FLAGS)
Write on the specified socket.

The following functions perform the same system function as defined for the UNIX system on which Perl is operating. Perl doesn't actually implement them; it just calls the UNIX system function. So if this function isn't available with your implementation of UNIX, it also isn't available with Perl. To get a complete explanation of these functions, use the UNIX man command (man endpwent, for example).

setgrent
sethostent(STAYOPEN)
setnetent(STAYOPEN)
setpgrp(PID,PGRP)
setpriority(WHIch,WHO,PRIORITY)
setprotoent(STAYOPEN)
setpwent
setservent(STAYOPEN)
setsockopt(SOCKET,LEVEL,OPTNAME,OPTVAL)

shift(ARRAY)
shift ARRAY
shift
Return the first element of the array and remove it from the array.
shutdown(SOCKET,HOW) Shuts down the socket using the system command with the flags specified in HOW.
sin(VALUE)
sin VALUE
sin
Specify the sine function.
sleep(VALUE)
sleep VALUE
sleep
Suspend the process for approximately VALUE.
socket(SOCKET,DOMAIN,
TYPE,PROTOCOL)
Opens a socket based on the supplied protocol.
socketpair(SOCKET1,SOCKET2,
DOMAIN,TYPE,PROTOCOL)
Creates an unnamed pair of sockets in the specified domain.
sort(SUBROUTINE LIST)
sort(LIST)
sort SUBROUTINE LIST
sort LIST
Sort and return the specified LIST.
splice(ARRAY,OFFSET,
LENGTH,LIST)
splice(ARRAY,OFFSET,LENGTH)
splice(ARRAY,OFFSET)
Remove the elements designated by OFFSET and LENGTH from an array, and replace them with the elements of LIST, if any. Return the elements removed from the array. The array grows or shrinks as necessary. If LENGTH is omitted, remove everything from OFFSET onward.
split(/PATTERN/,VALUE,LIMIT)
split(/PATTERN/,VALUE)
Separate VALUE into a LIST. Each time PATTERN is encountered, a new element in LIST is created.
split(/PATTERN/)
split
The elements created in LIST cannot be greater than LIMIT. If LIMIT is reached, the remainder of VALUE is placed in the last element of LIST.
sprintf(FORMAT,LIST) Returns a formatted string based on FORMAT.
sqrt(VALUE)
sqrt VALUE
sqrt
Specify a square root.
srand(VALUE)
srand VALUE
srand
Specify a random function.
stat(FILEHANDLE)
stat FILEHANDLE
stat(VALUE)
stat SCALARVARIABLE
Return a 13-element array giving the statistics for a file.
study(SCALAR)
study SCALAR
study
Prepare for pattern matches on SCALAR.
substr(VALUE,OFFSET,LEN) Beginning at OFFSET in VALUE and continuing for LEN characters, returns the substring of VALUE.
symlink(OLDFILE,NEWFILE) Creates a symbolic link of NEWFILE to OLDFILE.
syscall(LIST)
syscall LIST
system(LIST)
system LIST
Call the system call specified as the first element of the list, passing the remaining elements as arguments to the system call.
tell(FILEHANDLE)
tell FILEHANDLE
tell
Return the current file pointer position in FILEHANDLE.
telldir(DIRHANDLE)
telldir DIRHANDLE
Return the current directory pointer position in DIRHANDLE.
times Returns a four-element array giving the user and system times, in seconds, for this process and the children of this process.
umask(VALUE)
umask VALUE
umask
Set the current umask and return the old umask.
undef(VALUE)
undef VALUE
undef
Set VALUE to null.
unlink(LIST)
unlink LIST
unlink
Delete the files named in LIST.
unpack(TEMPLATE,VALUE) Takes the structure in VALUE and expands it based on TEMPLATE, returning the array value.
unshift(ARRAY,LIST) Adds LIST to the front of ARRAY and returns the new size of ARRAY.
utime(LIST)
utime LIST
Change the access and modification times on each file in LIST.
values(ASSOC_ARRAY)
values ASSOC_ARRAY
Return an array of the values of the associative array.
vec(VALUE,OFFSET,BITS) Treats a string as a vector of unsigned integers and returns the value of the bitfield specified.
wait Waits for a child process to terminate and returns the pid of the deceased process.
wantarray Returns True if the context of the currently executing subroutine is looking for an array value.
warn(LIST)
warn LIST
Print LIST to STDERR.
write(FILEHANDLE)
write(VALUE)
write
Print formatted output.

Miscellaneous Perl Rules

Here is a list of Perl rules that you should know:

GNU License Information

GNU Texinfo version adapted by Jeff Kellem <composer@Beyond.Dreams.ORG>.

Copyright 1989, 1990, 1991, 1992, 1993 Larry Wall Texinfo version

Copyright 1990, 1991, 1993 Jeff Kellem

Permission is granted to make and distribute verbatim copies of this quick reference manual provided the copyright notice and this permission notice are preserved on all copies.

Permission is granted to copy and distribute modified versions of this quick reference manual under the conditions for verbatim copying, provided also that the sections "GNU General Public License" and "Conditions for Using Perl" are included exactly as in the original, and provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one.

Permission is granted to copy and distribute translations of this quick reference manual into another language, under the above conditions for modified versions, except that the section "GNU General Public License" and this permission notice may be included in translations approved by the Free Software Foundation instead of in the original English.