Perl 5 Pocket Reference
Perl 5 Pocket Reference
Pocket Reference
Perl 5
Pocket Reference
Second Edition
Johan Vromans
O'REILLY"
Cambridge Koln Paris Sebastopol Tokyo
Perl 5 Pocket Reference, Second Edition
byjohan Vromans
0&
&£
This book is primed on acid-free paper with 85% recycled content,
15% post-consumer waste. O'Reilly & Associates is committed to
using paper with the highest recycled content available consistent
with high quality.
ISBN: 1-56592-495-9
Table of Contents
Introduction 1
Conventions 1
Command-Line Options 2
Syntax 3
Embedded Documentation 4
Data Types 6
Literal Values 6
Variables 8
Context 9
Operators and Precedence 10
Statements 11
Subroutines, Packages, and Modules 13
Object-Oriented Programming 15
Standard Methods 16
Pragmatic Modules 16
Arithmetic Functions 18
Conversion Functions 19
Structure Conversion 20
String Functions 21
Array and Hash Functions 22
Regular Expressions 25
Search and Replace Functions 27
File Test Operators 29
Pile Operations 30
Input/Output 32
Formatted Printing 35
Formats 37
Tying Variables 38
Directory Reading Routines 39
System Interaction 39
Networking 42
System V IPC 43
Miscellaneous 44
Information from System Databases 45
Special Variables 49
Special Arrays 53
Special Hashes 53
Standard Modules 54
Environment Variables ,„ 62
Multithreading 63
The Perl Compiler 63
The Perl Debugger 64
Perl 5
Pocket Reference
Introduction
The Perl 5 Pocket Reference is a quick reference guide to Larry
Wall's Perl program. It contains a concise description of all
statements, functions, and variables, and lots of other useful
information. It is based on Perl Version 5.005.
The purpose of the Pocket Reference is to aid users of Perl in
finding the syntax of specific functions and statements, and
the meaning of built-in variables. It is not a self-contained
user guide; basic knowledge of the Perl language is required,
ll is also not complete; some of the more obscure variants of
Perl constructs have been left out. But all functions and vari-
ables arc mentioned in at least one way they can be used.
for more information on Perl, visit the Perl w e b site at
bttp://wuw.perl.com.
Conventions
this denotes text that you enter literally.
this means variable text, i.e., things you must fill in.
tbis\ means that this will default to $_ if omitted,
word is a keyword, i.e.. a word with a special meaning.
RinxrKN | denotes pressing a keyboard key.
I... 1 denotes an optional part.
Conventions
Command-Line Options
-a Turns on autosplit mode when used with - n or - p .
Splits to @F.
-c Checks syntax but does not execute. It does run
BEGIN and END blocks.
-d( -.module 1
Runs the script under the indicated module. Default
module is the debugger. Use -deO to start the
debugger without a script.
-DJltigs Sets debugging flags.
- e commandtitw
May be used to enter a single line of script. Multiple
- e commands may be given to build up a multiline
script.
-Prvgex Specifies a regular expression to split on if - a is in
effect,
-h Prints die Perl usage summary. Does not execute.
-text Files processed by the < > construct are to be edited
in place.
-Idir The directory is prepended to the search path for
Perl modules. ©INC. With - P , also tells the C
preprocessor where to look for include files.
-l( octnum 1
(That's the letter ell.) Enables automatic line-end
processing, e.g., -1013.
-mmodule
Imports the module before executing the script.
module may be followed by an equals sign and a
comma-separated list of items.
-Mmodule
Same as -m, but with more trickery.
-n Assumes an input loop around the script. Lines are
not printed.
Syntax
Perl is a free-format programming language. This means that
in general, it does not matter how a Perl program is written
with regard to indentation and lines.
Syntax
An exception to this rule is when the Perl compiler encoun-
ters a sharp or pound symbol (#) in the input: it then discards
this symbol and everything following it up to the end of the
current input line. This can be used to put comments in Perl
programs. Real programmers put lots of useful comments in
their programs.
There are places where whitespace does matter: within literal
texts, patterns, and formats.
If the Perl compiler encounters the special token END , it
discards this symbol and stops reading input. Anything fol-
lowing this token is ignored by the Perl compiler, but can be
read by the program when it is run.
When Perl is expecting a new statement and encounters a
line that starts with =, it skips all input up to and including a
line mat starts with =cut. This is used to embed program
documentation.
Embedded Documentation
Tools exist to extract embedded documentation and generate
input suitable for several formatters like troff, iATfcX, and
HTML. The following commands can be used to control
embedded documentation:
=back See =over.
=begin FMT
Subsequent text up to a matching =end is only
included when processed for formatter FMT.
=cut Ends a document section.
=end FMT
See =begin.
=for FMT
The next paragraph is only included when pro-
cessed for formatter FMT.
Embedded Documentation
X<index>
An index entry.
Z<> A zero-width character.
Data Types
Array Indexable list of scalar values
Hash Associative list of scalar values
Scalar Strings, numbers, and references
Literal Values
Array (1, 2, 3) is a list of three elements.
(1. 2, 3)[0] is the first element from this list,
(1,2, 3)[-l] the last element.
( ) is an empty list.
(1..4) is the same as (1,2,3,4),
likewise ( ' a ' . . ' z ' ) .
( ' a ' „ ' z ' ) [ 4 , 7 , 9 ] is a slice of a list literal.
qw/foo bar .../ is the same as ( ' f o o ' , ' b a r ' , . . . ) .
Array reference
[1,2,3]
Array reference with named indices (pseudo-hash)
[(field 1 => l,field2 => 2. ... J]
Boolean
Perl has no boolean data type. Anything that is
undefined or evaluates to the null string, the number
zero, or the string "0" is considered false, everything
else is true (including strings like "00"!).
Code reference
sub { statements)
Filehandles
STDIN. STDOIJT. STDERR, ARGV, DATA.
User-specified: handle, $var.
Literal Values
encountered. \Q quotes non-word characters until a
\E is encountered.
"command"
Evaluates to the output of the command. Also:
qx/command/.
Variables
$var A simple scalar variable.
$var[27]
28th element of array @var.
$p = \@var
Now Sp is a reference to array @var.
$$p[27]
28th element of array referenced by $p.
Also, $p->(27].
$varl-l]
Last element of array @var.
$varl$i|[$j]
Sj-th element of $i-th element of array @var.
$var{' Feb'}
A value from hash %var.
$p = \%var
Now $p is a reference to hash %var.
$$p('Feb'|
A value from hash referenced by $p.
Also. $p->{'Feb'J.
$»var Last index of array @var.
@var The entire array; in scalar context, the number of
elements in die array.
@var[ 3,4,51
A slice of array ®var.
©varJ'aVb'J
A slice of %var; same as ($var{' a ' },$var{' b'}).
Context
Boolean
A special form of scalar context in which it only
matters if the result is true or false.
List A list value or an array is expected.
Scalar A single scalar value is expected.
Void No value is expected. If a value is provided, it is
discarded.
The following functions relate to context:
scalar expr
Forces scalar context for the expression.
wantarray
Returns true if the current context expects a list
value, undef in void context.
Context
Operators and Precedence
Perl operators have the following associativity and prece-
dence, listed from highest precedence to lowest.
Assoc. Operators Description
terms and
left See below.
list operators
left -> Infix dereference operator.
++ Auto-increment (magical on strings).
Auto-decrement.
right »* Exponentiation.
right \ Reference to an object (unary).
right t Unary negation, bitwise complement.
right + - Unary plus, minus.
left Binds a scalar expression to a pattern
match.
left \- Same, but negates the result.
left * / % X Multiplication, division, modulo,
repetition.
left + - . Addition, subtraction, concatenation.
left » « Bitwise shift right, bitwise shift left.
named unary
operators
e.g., sin. chdir. -f. -M.
Numerical relational operators.
tt gt le ge String relational operators.
== != <=> Numerical equal, not equal, compare.
eq ne emp Stringwise equal, not equal, compare.
Compare operators return -1 (less),
0 (equal), or 1 (greater).
left & Bitwise AND.
left 1 * Bitwise OR, exclusive OR.
left && Logical AND.
left II Logical OR.
In scalar context, ninge operator.
In list context, enumeration.
Alternative range operator.
right •>• Conditional (if ? then : else) operator.
Statements
A statement is an expression, optionally followed by a modi-
fier, and terminated with a semicolon. Statements can be
combined to form a block when enclosed in {}. The semi-
colon may be omitted after the last statement of the block.
Statetnents 11
Execution of expressions can depend on other expressions
using one of the modifiers if, unless, for, foreach, while, or until,
e.g.:
exprl if e.xprj;
exprl foreach list;
exprl until expr2:
The logical operators I I, &&, or?: also allow conditional
execution:
exprl | | exfirJ;
ex/>rl ? e.xprj: exprj;
blocks may be used to control flow:
if ( expr) block 11 elsif (iwpn block...] else block I
Object-Oriented Programming
Perl rules of object-oriented programming are as follows:
• An object is simply a reference that happens to know
which class it belongs to. Objects are blessed, references
are not.
• A class is simply a package that happens to provide meth-
ods to deal with object references. If a package fails to
provide a method, the base classes as listed in ©ISA are
searched.
• A method is simply a subroutine that expects an object
reference (or a package name, for static methods) as the
first argument.
Methods can be called with:
ohjtvf—> method parameters or
method ohjrefparameters
Object-Oriented Programming 15
Standard Methods
The package UNIVERSAL contains methods that are automati-
cally inherited by all other classes:
can method
Returns a reference to the method if its object has it,
undef otherwise,
isa class
Returns true if its object is blessed into a subclass of
class.
VERSION [ need I
Returns the version of the class. Checks the version
if need is supplied.
Pragmatic Modules
Pragmatic modules affect die compilation of your program.
Pragmatic modules can be activated (imported) with use and
deactivated with no. These are usually block scoped.
attrs attributes
Sets/gets attributes of a subroutine,
use attrs "method" indicates that the invoking sub-
routine is a method.
use attrs "locked" protects the invoking subroutine
against concurrent access.
autouse mods
Each of the named modules will not be loaded until
one of its functions is called.
base classes
Establishes an IS-A relationship with the base classes
at compile time,
blib [ dir ]
Uses MakeMaker's uninstaller! version of a package.
dir defaults to the current director)'.
Pragmatic Modules 17
strict [ constructs ]
Restricts unsafe constructs,
use strict "refs" restricts the use of symbolic
references.
use strict "vars" requires all variables to be either
my or fully qualified.
use strict "subs" restricts the use of bareword iden-
tifiers that are not subroutines.
Without constructs, affects all of them.
subs names
Predeclares subroutine names, allowing you to use
them without parentheses even before they are
declared.
Example: use subs qw(ding dong);
vars names
Predeclares variable names, allowing you to use
them under the strict pragma.
Example: use vars qw($foo ©bar);
vmsish [ features \
Controls VMS-specific language features. VMS only.
use vmsish "exit" enables VMS-style exit codes.
use vmsish "status" allows system commands to
deliver VMS-style exit codes to the calling program.
use vmsish "time" makes all limes relative to the
local time zone.
Without features, affects all of them.
Arithmetic Functions
abs exprf Returns the absolute value of its operand.
atan2 y, x Returns the arctangent of y/x in the range -n to it.
cos expr\ Returns the cosine of expr (expressed in radians),
exp expri Returns e to the power of expr.
int expr] Returns the integer portion of expr.
Conversion Functions
chr expr\
Returns the character represented by the decimal
value expr.
gmtime I expr ]
In list context, converts a lime as returned by the
time function to a 9-elemenl list (0:$sec\ l:$min,
2:$hour, 3:$mday, 4:$mon, 5:$year, 6:$wday,
7:$yday, 8:$isdst) with the time localized for the
standard Greenwich time zone.
In scalar context, converts it to print format.
$mon has the range 0 (January) .. 11 (December)
and $wday has the range 0 (Sunday) .. 6 (Saturday).
expr defaults to the current time,
hex exprf
Returns the decimal value of expr interpreted as a
hex siring,
localtime I expr ]
Like gmtime, but with the time localized for the local
time zone.
Conversion Functions 19
oct expr\
Returns the decimal value of expr interpreted as an
octal string. If expr starts off with Ox, interprets it as
a hex string instead.
ord expr\
Returns the ASCII value of the first character of expr.
vec expr, offset, bits
Treats string expr as a vector of unsigned integers of
bits bits each, and yields the decimal value of the
element at offset, bits must be a power of 2 between
1 and 32. May be assigned to.
Structure Conversion
pack template, list
Packs the values in list into a binary structure using
template. Returns a string containing the structure.
unpack template, expr
Unpacks the structure expr into a list, using template.
template is a sequence of characters as follows:
a / A ASCII string, null- / space-padded
b / B Bit string in ascending / descending order
c / C Signed / unsigned char value
f / d Single / double float in native format
h / H Hex string, low / high nybble first
i / I Signed / unsigned integer value
1 / L Signed / unsigned long value
n / N Short / long in network (big endian) byte order
s / S Signed / unsigned short value
u / P Uuencoded string / pointer to a string
P Pointer to a structure (fixed-length string)
V / V Short / long in VAX (little endian) byte order
w A BER compressed integer
X / ® Null byte / null fill until position
X Back up a byte
String Functions
chomp fe/f
Removes line endings from all elements of the list;
returns the (total) number of characters removed.
chop Iist\
Chops off' the last character on all elements of the
list; returns the last chopped character.
crypt plaintext, salt
Encrypts a string (irreversibly).
eval expr\
expr is parsed and executed as if it were a Perl pro-
gram. The value returned is the value of the last
expression evaluated. If there is a syntax error or
runtime error, undef is returned by eval, and $@ is set
to the error message. See also eval in the section
"Miscellaneous."
index sir, substr [ , offset I , replacement ] ]
Returns die position of substr in str ai or after offset.
Replaces the found substring by the replacement
text if specified. If the substring is not found,
returns -1.
Ic exprf Returns a lowercase version of expr.
Icfirst e\pr\
Returns expr with iis first character in lowercase.
length expr\
Returns the length in bytes of expr.
quotemeta expr\
Returns expr with all regular expression metacharac-
ters quoted.
String Functions 21
rindex sir, substr I , offset |
Returns the position of the last substr in sir at or
before offset.
substr expr, qffsel I , leu 1
Extracts a substring of length ten starting at qffsel out
of expr and returns it. If offset is negative, counts
from the end of the string. If len is negative, leaves
that many characters off the end of the string. May
be assigned to.
uc expr\
Returns an uppercase version of expr.
ucfirst expr]
Returns expr with its first character in uppercase.
Regular Expressions 25
(?l code))
Executes Perl code while matching. Always succeeds
with zero width.
Requires the re "eval" pragma.
(?> regex)
Anchored subpattem.
O(.cond)ptrue [ I pfalse ] )
Selects a pattern depending on the condition, cond
should be the number of a parenthesised subpat-
tem, or one of the zero-width look-ahead, look-
behind and evaluate assertions.
0 modifier)
Embedded pattern-match modifier, modifier can be
one or more of i, m, s, orx. Modifiers can be
switched off by preceding the letter(s) with a minus
sign.
Quantified subpatterns match as many times as possible.
When followed with a ? they match the minimum number of
times. These are the quantifiers:
+ Matches the preceding pattern element one or more
times.
? Matches zero or one times.
* Matches zero or more times.
{«,»«) Denotes the minimum n and maximum m match
count. («} means exactly n times; {«,) means at least
n times.
A \ escapes any special meaning of the following character if
non-alphanumeric, but it turns most alphanumeric characters
into something special:
\w Matches alphanumeric, including _, \W matches
non-alphanumeric.
\s Matches whitespace, \S matches non-whitespace.
\d Matches digits, \D matches non-digits.
File Operations
Functions operating on a list of files return the number of
files successfully operated upon.
chmod list
Changes the permissions of a list of files. The first
element of the list must be the numerical mode in
octal, e.g., 0644.
chown list
Changes the owner and group of a list of files. The
first two elements of the list must be the numerical
uid and gid. If gid is - 1 , the group is not changed.
File O(terations 31
Input/Output
In input/output operations, filehandle may be a filehandle as
opened by the open operator, a predefined filehandle (e.g.,
STDOUT) or a scalar variable that evaluates to a reference to
or the name of a filehandle to be used.
<filehandle>
In scalar context, reads a single line from the file
opened on filehandle. In list context, reads the rest
of the file.
<> Reads from the input stream formed by the files
specified in @ARGV, or standard input if no argu-
ments were supplied.
binmode filehandle
Arranges for the file opened on filehandle to be read
or written in binary mode as opposed to text mode
(null operation on Unix or Mac).
close I filehandle ]
Closes the file or pipe associated with the filehandle.
Resets $.. Iffilehandleis omitted, closes the cur-
rently selected filehandle.
dbmclose %bash
Deprecated, use untie instead.
dbmopen %basb, dbmnattte, mode
Deprecated, use tie instead.
eof filehandle
Returns true if the next read will return end of file, or
if the file is not open.
eof Returns the EOF status for the last file read.
eof() Indicates EOF on the pseudo-file formed of the files
listed on the command line.
fcntl filehandle, function, %uar
Implements the/c«f/(2) function. This function has
nonstandard return values.
Input/Output 33
• and I"
Opens a pipe from command cmd, forks if
and is -.
file may be &filehnd, in which ease the new file-
handle is connected to the (previously opened)
filehandle JiMmd. If it is &=n,fite will be connected
to the given file descriptor,
open returns undef upon failure, true otherwise.
pipe readhandle, writehandle
Returns a pair of connected pipes.
print I fitehattdle 1 I list\ ]
Prints the elemenis of list, converting them to strings
if needed. Iffilehandleis omitted, prints by default
to standard output (or to the last selected output
channel; see select).
printf I fitehattdle \\ list]
Equivalent to printfilehandtespnnlt list.
read filehandte, %var, length I, offset ]
Reads length binary bytes from die file into the vari-
able at offset. Returns number of bytes actually read,
0 on eof, and undef on failure.
readline expr
Internal function that implements the <> operator.
expr must be a typeglob.
readpipe expr
Internal function that implements the qx// operator.
expr is executed as a system command,
seek filehandte, [iosition, whence
Arbitrarily positions the file. Returns true if
successful,
select 1 filehandte )
Returns die currendy selected filehandle. Sets the
current default filehandle for output operations if
filehandle is supplied.
Formatted Printing
printf a n d sprintf format a list of values according to a fonnat
string that may u s e the following conversions:
%% A percent sign.
%c The character corresponding to the ordinal value.
%d A signed integer.
Formatted Printing 35
%e A floating-point number (scientific notation).
%f A floating-point number (fixed decimal notation).
%g A floating-point number (%e or %f notation).
%i A synonym for %d.
%n The number of characters formatted so far is stored
into the corresponding variable in the parameter list.
%o An unsigned integer, in octal.
%p A pointer (address in hexadecimal).
%s A string.
%u An unsigned integer (decimal).
%x An unsigned integer (hexadecimal).
%D An obsolete synonym for %ld.
%E Like %e, but using an uppercase "E".
%F An obsolete synonym for %f.
%G Like %g, but with an uppercase "E" (if applicable).
%0 An obsolete synonym for %lo.
%U An obsolete synonym for %lu.
%X Like %xT but using uppercase letters.
The following flags can be put between the % and the conver-
sion letter:
space Prefix a positive number with a space.
+ Prefix a positive number with a plus sign.
Left-justify within the field.
0 Use zeroes instead of spaces to right-justify.
* Prefix a non-zero octal number with "0", and a non-
zero hex number with "Ox".
number Minimum field width.
.number
For a floating-point number: the number of digits
after the decimal point.
For a string: the maximum length.
For an integer: the minimum width.
Formats
formline picture, list
Formats list according to picture and accumulates the
result into $"A.
write I filehanclle I
Writes a formatted record to the specified file, using
the formal associated with that file.
Iffilehanclle is omitted, the currently selected one is
taken.
Formats are defined as follows:
format I name I =
formlist
Formats 37
Picture fields are:
@<«... Left-adjusted field. Repeat the < to denote
the desired width.
@>»... Right-adjusted field.
@l 1 1... Centered field.
©#.##.., Numeric format with implied decimal point.
@> Multiline field.
Use * instead of® for multiline block filling.
Use ~ in a picture line to suppress unwanted empty lines.
Use ~" in a picture line to have this format line repeated until
all fields are exhausted.
Set $- to zero to force a page break on the next write.
See also $*, $", $"A, $"F, $-, and $= in the section 'Special
Variables."
Tying Variables
tie var, ctassname, [ list )
Ties a variable to a package class that will handle it.
list is passed to the class constructor,
tied var Returns a reference to the object underlying var, or
undef if var is not tied to a package class,
untie var
Breaks the binding between the variable and the
package class.
A class implementing a tied scalar should define die methods
TIESCALAR, FETCH, STORE, and possibly DESTROY.
A class implementing a tied ordinary array should define the
metliods TIEARRAY, FETCH, STORE, FETCHSIZE, STORESIZE,
and perhaps DESTROY.
System Interaction
alarm expr
Schedules a SIGALRM to be delivered after expr sec-
onds. If expris 0, cancels a pending timer.
System Interaction 39
chdir I expr )
Changes the working directory. Uses $ENV{HOME)
or SENVfLOGNAME} if expr is omitted.
chroot filename^
Changes the root directory for the process and its
children.
die [ list ]
Prints the value of list to STDERR and exits with the
current value of $! (errno). If $• is 0, exits with the
value of ($? » 8). If ($? » 8) is 0, exits with 255.
list defaults to "Died". Inside aneval, the error mes-
sage is stuffed into $@, and the evat is terminated
and returns undef; this makes die the way to raise an
exception.
exec ( program ] list
Executes the system command in list; does not
return, program can be used to designate the pro-
gram to execute command.
exit [ expr ]
Exits immediately with the value of expr, which
defaults to 0 (zero). Calls END routines and object
destructors before exiting.
fork Does afork(2) system call. Returns the process ID of
the child to the parent process (or undef on failure)
and zero to the child process.
getlogin Returns the current login name as known by the
system. If it returns false, use getpwuid.
getpgrp ( pid ]
Returns the process group for process pid (0, or
omitted, means the current process).
getppid Returns the process ID of the parent process.
getprtority which, who
Returns the current priority for a process, process
group, or user. Use getpriority 0,0 to designate the
current process.
System Interaction 41
umask ( expr \
Sets the umask for the process and returns the old
one. If expr is omitted, returns current umask value.
wait Waits for a child process to terminate and returns
the process ID of the deceased process (-1 if none).
The status is returned in $?.
waitpid pid, flags
Performs the same function as the corresponding
system call. Returns 1 when process pid is dead, -
-1 if nonexistent.
warn I list \
Prints list on STDERR like die, but doesn't exit, list
defaults to "Warning: something's wrong".
Networking
accept newsocket, genericsockel
Accepts a new socket,
bind socket, name
Binds the name to the socket.
connect socket, name
Connects the name to the socket,
gelpeername socket
Returns the socket address of the other end of the
socket.
getsockname socket
Returns the name of the socket,
getsockopt socket, level, optname
Returns the socket options,
listen socket, queuesize
Starts listening on the specified socket, allowing
queuesize connections,
recv socket, Svar, length, flags
Receives a message on socket of length bytes into
scalar variable Svar.
System VIPC
Depending on your system configuration, certain system files
need to be required to access the message- and semaphore-
specific operation names.
msgctl id, and, args
Calls msgc(Kl). If cmd is &IPC_STAT then args must
be a variable. See the Perl documentation for details
on the nonstandard return values of this function,
msgget key,jlags
Creates a message queue for key. Returns the mes-
sage queue identifier,
msg rev id, $uar, size, type, flags
Receives a message from queue iV/into $var.
msgsnd id, msg, flags
Sends msg to queue id.
semcll id. semnum, cmd, arg
Calls semctld). If cmd is &IPC.STAT or &GETALL
then arg must be a variable.
semget key, nsems, size, flags
Creates a set of semaphores for key. Returns die
message semaphore identifier.
System VIPC 43
semop key, ...
Performs semaphore operations,
shmctl id, and, arg
Calls shmctKl). If and is &IPC_STAT then arg must
be a scalar variable,
shmget key, size, flags
Creates shared memory. Returns the shared memory
segment identifier,
shmread id, $var, pos, size
Reads at most size bytes of die contents of shared
memory segment id starting at offset pos into Svar.
shmwrite id, string, pos, size
Writes at most size bytes of siring into the contents
of shared memory segment id at offset pos.
Miscellaneous
defined expr
Tests whether the expr has an actual value.
do filename
Executesfilenameas a Perl script. See also require in
the section "Subroutines, Packages, and Modules."
dump [ label ]
Immediate core dump. When reincarnated, starts at
label. Obsolete.
eval ( expr, ...)
Executes the code between I and I. Traps runtime
errors and returns as described with eva\(expr), in
the section "String Functions."
local variable
Gives a temporary value to the named package vari-
able, which lasts until the enclosing block, file, or
eval exits.
Special Variables 49
$[ The index of the first element in an array or list, and
of the first character in a substring. Default is 0.
Deprecated. Do not use.
$; Alternative: SSUBSCRlPT_SEPARATOR, SSUBSEP.
The subscript separator for multidimensional list
emulation. Default is "\034".
$! Alternative: $OS_ERROR, SERRNO.
Used in a numeric context, yields the current value
of errno. Used in a suing context, yields the corre-
sponding error string.
5® Alternative: $EVAL_ERROR.
The Perl error message from the last eval or do expr
command.
$: Alternative: $FORMAT_LINE_BREAK_CHARACTERS.
The set of characters after which a string may be
broken to fill continuation fields (starting with *) in
a format.
$0 Alternative: SPROGRAM.NAME.
The name of the file containing the Perl script being
executed. May be assigned to.
$$ Alternative: SPROCESSJD, $PID.
The process ID of the Perl interpreter running this
script. Altered (in the child process) by fork.
$< Alternative: $REAL_USER_ID, $UID.
The real user ID of this process.
$> Alternative: $EFFECnVE_USER_lD, $EU1D.
The effective user ID of this process.
$( Alternative: $REAL_GROUP_ID. SGID.
The real group ID, or space-separated list of group
IDs, of this process.
$) Alternative: $EFFECnVE_GROUP_!D, SEGID.
The effective group ID. or space-separated list of
group IDs, of this process.
$~A Alternative: $ ACCUMULATOR.
The accumulator for formline and write operations.
Special Variables 51
$- Alternative: $FORMAT_LINES_LEFT.
The number of lines remaining on the page.
$~ Alternative: $FORMAT_NAME.
The name of the current report format.
$* Alternative: SFORMAT_TOP_NAME.
The name of the current top-of-page format.
$1 Alternative: SOUTPUT_AUTOFLUSH.
If set to nonzero, forces a flush after every write or
print on the currently selected output channel.
Default is 0.
SARGV The name of the current file when reading from < >.
The following variables are always local to the current block:
$& Alternative: SMATCH.
The string matched by the last successful pattern
match.
$' Alternative: SPREMATCH.
The siring preceding what was matched by the last
successful match.
$' Alternative: SPOSTMATCH.
The string following what was matched by the last
successful match.
$+ Alternative: $LAST_PAREN_MATCH.
The last bracket matched by the last search pattern.
$1...$9...
Contain the subpatterns from the corresponding sets
of parentheses in the last pattern successfully
matched. $10 and up are only available if the match
contained that many subpatterns.
Special Hashes
%ENV Contains the current environment. The key is the
name of an environment variable; the value is its
current setting.
%EXPORT_TAGS
Defines names for sets of symbols.
%1NC List of files that have been included with use, require,
or do. The key is the filename as specified: the value
the location of the file.
Special Hashes S3
%SIG Used to set signal handlers for various signals. The
key is the name of the signal (without the SIG pre-
fix); the value a subroutine that is executed when
the signal occurs.
„WARN and DIE are pseudo-signals to
attach handlers to Perl warnings and exceptions.
Standard Modules
AnyDBM_FUe
Provides a framework for multiple dbm files.
AutoLoader
Loads functions only on demand.
AutoSplit
Splits a package for autoloading.
B Experimental package that implements byte compi-
lation, a Perl to C translator, and other interesting
things.
Benchmark
Benchmarks running times of code.
Bundle::CPAN
A bundle to play with all the oilier modules on
CPAN.
Carp Warns of errors.
CGI Simple Common Gateway Interface Class.
CGI::Apache
CGI addition for Apache's Perl API.
CGI::Cookie
Interface to Netscape Cookies.
CGl:Fast
CGI interface for FastCGl.
CGI.Push
Simple interface to Server Push.
Standard Modules 55
ExtUtlls::Manifest
Utilities to write and check a MANIFEST file.
ExtUtils-Miniperl
Writes the C code for perlmain.c.
ExtUtils:: Mkbootstrap
Makes a bootstrap file for use by DynaLoader.
ExtUtils: :Mksymlists
Writes linker options files for dynamic extension.
ExtUtils: :MM_OS2
Methods to override Unix behavior in
ExtUtils::MakeMaker.
ExtUtils::MM_Unix
Methods used by ExtUtils: :MakeMaker.
ExtUtils::MM_VMS
Methods to override Unix behavior in
ExtUtils;: MakeMaker.
ExtUtils: :MM_Win32
Methods to override Unix behavior in
ExtUtils::MakeMaker.
ExtUtils-Packlist
Manages packlist files.
ExtUtils:: test lib
Adds blib directories to ©INC.
Fatal Replaces functions with equivalents that succeed or
die.
Fcntl Loads the C fcntl.h defines.
Fite::Basename
Parses file specifications.
File::CheckTree
Runs many filetest checks on a tree.
File::Copy
Copies files or filehandles.
File::DosGlob
DOS-like globbing (with extensions).
Standard Modules 57
IO Loads various I/O modules.
IO::File Supplies object methods for filehandles.
IO::Handle
Supplies object methods for I/O handles.
IO::Pipe
Supplies object methods for pipes.
IO::Seckable
Supplies seek-based methods for I/O objects.
IO::Select
Object interface to the select system call.
IO::Socket
Object interface to socket communications.
IPC::Msg
Interface to System V Message IPC.
IPC::Open2
Open a pipe to a process for both reading and
writing.
IPC:;Open3
Open a pipe to a process for reading, writing, and
error handling.
IFC::Semaphore
Interface to System V semaphores.
IPC::SysV
System V IPC object class.
Math::BigFloat
Arbitrary length float math package.
Math::BigInt
Arbitrary size integer math package.
Math::Complex
Complex numbers and associated mathematical
functions.
NDBM_File
tied access to ndbm files.
Standard Modules 59
Select Saver
Saves and restores a selected filehandle.
SellLoader
Loads functions only on demand.
Shell Runs shell commands transparently within Perl.
Socket Loads the C socket.h defines and structure
manipulators.
Symbol Manipulates Perl symbols and their names.
Sysr.Hostname
Tries every conceivable way to get the name of this
system.
Sys::Syslog
Interface to the Unix S)>slog(3) calls.
Term::Cap
Perl interface to Unix lerntcap(3)-
Term::Complete
Word completion module.
Term::ReadLine
Interface to various readline packages.
Test::Harness
Runs Perl standard test scripts with statistics.
Text::Abbrev
Creates an abbreviation table from a list.
Text::ParseWords
Parses text into a list of tokens.
Text::Soundex
Implementation of the Soundex Algorithm as
described by Donald Knuth.
Text::Tabs
Expands and unexpands tabs.
Text:: Wrap
Line wrapping to form simple paragraphs.
Thread Implementation of Perl threads.
Standard Modules 61
VMS::DCLsym
Perl extension to manipulate DCL symbols. VMS
only.
VMS::Filespec
Converts between VMS and Unix file specification
syntax. VMS only.
VMS::Stdio
Standard I/O functions via VMS extensions. VMS
only.
VMS::XSSymSet
Keeps sets of symbol names palatable to the VMS
linker.
Environment Variables
Perl uses the following environment variables:
HOME Used if chdir has no argument.
LOGDIR
Used if chdlr has no argument and HOME is not set.
PATH Used in executing subprocesses, and in finding the
Perl script if-S is used.
PERL5LIB
A colon-separated list of directories to look in for
Perl library files before looking in the standard
library and the current directory.
PERL5DB
The command to get the debugger code. Defaults to
BEGIN {require 'perl5db.pl' }.
PERLLIB
Used instead ofPERL5LD3 if the latter is not defined.
Mastering Algorithms
Advanced Perl Programming with Perl
bySriram Srinirasan by Jon Orutmt, Jorkko llietanieini
1st Edition August 1997 6 John Macdotmld
ISBN 1-56592-2204 1st Edition Sefttember 1998
ISBN 1-56592-398-7
O'REILLY"
waw-f 800-998-9938 * order@or8illy.com • http://www.oreilly.com/
OUR PRODUCTS AW A/AHASU HI A SOOKSICPS OR SGI WAM srcsi KM YOU
FOBmrommon: 800-998-9938 * 707-829-0515 • lttto@OTelUy.eom
O'REILLY
9 781565"924956 6 3692u"92495 M 1