Rex Swain's HTMLified

Perl 5 Reference Guide

adapted by Dennis German
Literals
Variables
Operators
Statements
Subroutines,
   Packages and Modules

Object-Oriented Programming
Arithmetic Functions
Conversion Functions
Structure Conversion
String Functions
Array and List Functions
Command-Line Options

The Perl Debugger

Regular Expressions
Search and Replace
File Test Operators
File Operations
Input / Output
Formats
Directory Reading
System Interaction
Networking
System V IPC
Miscellaneous
Infor from System Files
Special Variables
Special Arrays
Environment Variables

Index

abs
accept
alarm
and
ARGV
ArithmeticFunctions
ArrayListFunctions
ArraysSpecial
atan2

BEGIN
bind
binmode
bless

caller
chdir
chmod
chomp
chop
chr
chroot
close
closedir
cmp
CommandLineOptions
connect
Contents
continue
Conventions
ConversionFunctions
ConversionStructure
cos
crypt

dbmclose
dbmopen
Debugger
defined
delete
die
Directory
do
dump

each
else
elsif
END
ENV
EnvironmentVariables
eof
eq
eval
eval
exec
exists
exit
exp
EXPORT
EXPORT_OK
ExpressionsRegular

fcntl
fileno
FileOperations
FilesSystemInformationFrom
FileTestOperators
flock
for
foreach
fork
Formats
formline
FunctionsArithmetic
FunctionsArrayList
FunctionsConversion
SearchReplace
FunctionsString

getc
getlogin
getpeername
getpgrp
getppid
getpriority
getsockname
getsockopt
glob
gmtime
goto
goto subroutine
grep

hex
HOME

if
import
INC
index
InformationFromSystemFiles
InputOutput
int
InteractionSystem
ioctl
ISA

join

keys
kill

last
lc
lcfirst
length
link
ListArrayFunctions
listen
Literals
local
localtime
log
LOGDIR
lstat

match
map
Miscellaeous
mkdir
Modules
my

Networking
next
no module
npt

ObjectOrientedProgramming
oct
open
opendir
OperationsFile
Operators
OperatorsFileTest
OptionsCommandLine
or
ord
OutputInput
OVERLOAD

pack
package
Packages
PATH
PERL5DB
PERL5LIB
PERLLIB
pipe
pop
pos
print
printf
push
quotemeta

rand
read
readdir
readlink
recv
redo
ref
RegularExpressions
rename
ReplaceSearch
require
reset
return
reverse
rewindir
rindex
rmdir

s
scalar
scalar
SearchReplace
seek
seekdir
select
send
setpgrp
setpriority
setsockopt
shift
shutdown
SIG
sin
sleep
socket
socketpair
sort
SpecialArrays
SpecialVariables
splice
split
sprintf
sqrt
srand
stat
Statements
StringFunctions
StructureConversion
study
sub
Subroutines
substr
symlink
syscall
sysread
system
File Info
SystemInteraction
SystemVIPC
syswrite


tell
telldir
TestFileOperators
tie
time
times
tr
truncate


uc
ucfirst
umask
undef
unless
unlink
unpack
unshift
untie
until
until
use
utime

values

Variables
VariablesEnvironment
VariablesSpecial
vec

wait
waitpid
wantarray
warn
while
write


xor
y

Document Conventions

fixed denotes literal text. word is a keyword, i.e., a word with a special meaning.
THIS means variable text, i.e., things you must fill in. RETURN key   denotes pressing a keyboard key.
THIS£ means that THIS will default to $_ if omitted. […] denotes an optional part.

Quoting:

'abc' except \' and \\

No $variable or escape sequences intreptation
print 'This will NOT output the $answer';

q/abc/
Almost any pair of delimiters can be used instead of //.
"abc"

$variables are intrepreted and escape sequences are processed.
print "The answer is $answer \n";

qq/abc/.
`command`

evaluates to the output of the command.

qx/command/.

Escape sequences:

Literals

Numeric: 123, 1_234, 1.234, 5E-10, 0xff (hex), 0377 (leading zero implies octal)

Variables

$var simple scalar
$var[28] 29th element of array @var.
$p = \@var now $p is a reference to array @var.
$$p[28]
$p->[28]
29th element of array referenced by $p.
$var[-1] last element of array @var.
$var[$i][$j] $jth element of the $ith element of array @var.
$#var last index of array @var.
@var the entire array. In a scalar context, the number of elements in the array.
@var[3,4,5] a slice of array @var.
@var{'a','b'}
($var{'a'},$var{'b'})
a slice of %var;
%var the entire hash. In a scalar context, true if the hash has elements.
$var{'Feb'} a value from hash %var.
$p = \%var now $p is a reference to hash %var
$p->{'Feb'}.
$$p{'Feb'}
a value from hash referenced by $p
$var{'a',1,} emulates a multidimensional array.
('a''z')[4,7,9] a slice of an array literal.
PKG::var a variable from a package, e.g., $pkg::var, @pkg::ary.
\OBJECT reference to an object, e.g., \$var, \%hash.
*NAME refers to all objects represented by NAME.
*n1 = *n2 makes n1 an alias for n2.
*n1 = $n2 makes $n1 an alias for $n2.

Array

@values(1, 2, 3)
@values(1..4) aka @values(1,2,3,4)
@values('a'..'z')
@values qw/foo bar / is the same as

('foo','bar',).

Array reference

$value[1,2,3]

Hash

(associative array)

initalze:
%myhash(KEY1,val1, KEY2,val2,)
Also
%myhash(KEY1=>val1, KEY2=>val2,)


reference:

$myhash{KEY1,val1, KEY2,val2,}

Use a {block} to return the correct type of reference instead of the variable identifier,
Example: ${},
&{}.
$$p is a shorthand for ${$p}.

Contents

Operators

** Exponentiation
+ -  * /  Addition, subtraction, multiplication, division
% Modulo division i.e. remainder
& | ^ Bitwise AND, OR, exclusiveOR
>> << Bitwise shift right, left
|| && Logical OR, AND
. string Concatenation
x left operand (an array or a string) repeated the number of times specified right operand
All of the above operators also have an assignment operator, e.g., .=
 
-> Dereference operator
\ Reference (unary)
! ~ Negation (unary), bitwise complement (unary)
++ -- Auto-increment (magical on strings), auto-decrement

Logical operators return 1 for true ( So don't use $xxPresent=true; )
Numeric String
== != equality, inequality eq ne
< > less than, greater than lt gt
<= >= less (greater) than or equal to le ge
<=> compare. Returns -1, 0, 1. cmp
=~!~ negate Search pattern, substitution, or translation
.. Range (scalar context) , enumeration (array context)
?: Alternation (if-then-else)
, Comma operator, also list element separator.
=> Comma operator, also list element separator.
not Low-precedence negation
and Low-precedence AND
or xor Low-precedence OR, exclusiveOR

All functions can be used as list operators, in which case they have very high or very low precedence, depending on whether you look at the left or the right side of the operator.
Operators not, and, or and xor have lower precedence.

A "list" is a list of expressions, variables, or lists.
An array variable or an array slice may be used instead of a list.

Parentheses clarify precedence.

Contents

Statements

A statement is an expression, optionally followed by a modifier, terminated by a semicolon.
The semicolon may be omitted if the statement is the final one in a block.

Statements combined form a block when enclosed in {}.

Execution of expressions can depend on other expressions using a modifier.

Conditional execution: logical operators

Program flow can be controlled with:

which are guaranteed to perform block once before testing expr, and

which turns block into an expression.

Contents

Subroutines, Packages and Modules

do f, require f, or use f

sub name {
     @arrayOfAllArgs
aka @_;
     $firstArg
aka $_[1]; $_[2] aka xxx;… ;
     statments;
     return }


&SUBROUTINE LIST Executes a SUBROUTINE declared by sub , and returns the value of the last expression evaluated in SUBROUTINE.
SUBROUTINE can be an expression yielding a reference to a code object.
The & may be omitted if the subroutine has been declared before being used.
[sub] BEGIN { expr; … } Defines a setup block called before execution.
[sub] END { expr; … } Defines a cleanup block called prior to termination.
sub name { expr; … } Designates name as a subroutine.
Parameters are passed by reference as array @_.
Returns the value of the last expression evaluated.
bless ref [,package] Turns the object ref into an object in package. Returns the reference.
caller [expr] Returns an array ($package,$file,$line,…) for a specific subroutine call. caller returns this info for the current subroutine, caller(1) for the caller of this subroutine, etc. Returns false if no caller.
do subroutine list Deprecated form of &subroutine.
goto &subroutine Substitutes a call to subroutine for the current subroutine.
import module [ [version] list ]
no module [ list ] Cancels imported semantics. See use.
package name Designates the remainder of the current block as a package.
require expr£ If expr is numeric, requires Perl to be at least that version. Otherwise expr must be the name of a file that is included from the Perl library. Does not include more than once, and yields a fatal error if the file does not evaluate to a true value. If expr is a bare word, assumes extension .pm for the name of the file.
return expr
tie var, package, [list] Can be used to bind a dbm or ndbm file to a hash. example:
BEGIN { @AnyDBM_File::ISA = qw(DB_File GDBM_File NDBM_File SDBM_File); }
use AnyDBM_File ;
tie %fin, "AnyDBM_File",$filein, O_RDWR, 0600 or die "Cannot open:\"$ts\" $! \n";

If O_RDONLY assignments fail without warning! (example:$fin{$key}="0909";)

untie var Breaks the binding between the variable and the package.
use MODULE [ [VERSION] list ] Imports semantics from the named module into the current package.

Contents

Code reference:

sub {STATEMENTS}

Filehandles:

STDIN, STDOUT, STDERR, ARGV, DATA.
User-specified: HANDLE, $var.

Globs:

<pattern> evaluates to all filenames according to the pattern. Use <${var}> or glob $var to glob from a variable.

Here-Is:
<<identifier
Shell-style "here document."

Special tokens:
__FILE__: filename;
__LINE__: line number;
__END__: end of program;
remaining lines can be read using the filehandle DATA.

Contents

Object-Oriented Programming

Perl rules of object oriented programming:

Methods can be applied with:

Contents

Arithmetic Functions

exp expr£ e expr sin expr£ sine in radians
log expr£ natural logarithm (base e) cos expr£ cosine in radians
sqrt expr£ square root atan2 y,x  arctangent of y/x in the range -π to π.
min(list)
max (list)
avg (list)

not implemented!

abs expr£ absolute value
int expr£ integer portion
rand [ exprrandom fractional number
between 0 and expr.  
default: between 0 and 1.
srand [ expr ]    seed for rand
time seconds since January 1, 1970.
Suitable for gmtime and localtime.

Contents

Conversion Functions

localtime expr£     Converts a time as returned by the time function to ctime(3) string.
                  Sun Aug 15 20:26:21 2010

In array context, returns a 9-element array with the time analyzed for the local time zone.
$mon has the range 0..11 and $wday has the range 0..6.
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time); ## for display and log name
$month=(January,February,March,April,May,June,July,August,September,October,November,December)[$mon];
if ($mday< 10) { $mday= "0$mday" }; if (++$mon< 10) { $mon= "0$mon" }; $year = 1900 + $year;
if ($hour< 10) { $hour= "0$hour" }; if ( $min< 10) { $min= "0$min" }; if ( $sec< 10) { $sec = "0$sec" };
xx

gmtime expr£     Converts a time as returned by the time function to a 9-element array Greenwich

chr expr£     Returns the character represented by the decimal value expr.
hex expr£     Returns the decimal value of expr interpreted as a hex string.
oct expr£     Returns the decimal value of expr interpreted as an octal string.
exprs begining with 0x are intrepreted as hexidecimal. 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, and yields the bit at offset. bits must be between 1 and 32. May be assigned to.

Contents

Structure Conversion

pack template, list Packs the values into a binary structure using template.
unpack template, expr Unpacks the structure expr into an array, using template.

TEMPLATE is a sequence of characters as follows:

Character may be followed by a decimal repeat count; an asterisk (*) specifies all remaining arguments.
If the format is preceded with %N, unpack returns an N-bit checksum instead.
Spaces may be included in the template for readability purposes.

Contents

String Functions

chomp list£ Removes line endings from all elements of the list.
Returns total number of characters removed.
chop list£ Chops off the last character on all elements of the list.
Returns last chopped character.
crypt plaintext, salt Encrypts a string.
eval expr£ expr is parsed and executed as if it were a Perl program.
Returns value of the last expression evaluated.
If there is a syntax error or runtime error, an undefined string is returned by eval, and $@ error message. See eval Miscellaneous.
index str, substr[, offset ] position of the first substr in str at or after offset0 . If the substr is not found, returns -1
rindex str, substr[, offset] position of the last substr in str at or before offset0.( reverse index)
length expr£ length in characters of value of expr.
quotemeta expr regular expression metacharacters quoted.
substr expr, ±offset0 [,len]
                    [,repl]
substring of length len from expr.
If offset0 is negative, counts from the end of the string. May be assigned to.
 
lc expr lowercase
lcfirst expr first character lowercase.
uc expr UPPERCASED
ucfirst expr First character Uppercased.

Contents

Array and List Functions

See   use List::Util qw(first max maxstr min minstr reduce shuffle sum);

delete $HASH{KEY} Deletes value from the hash at KEY.
Returns the deleted value unless HASH is tied to a package that does not support this.
each %HASH Returns a 2-element array consisting of the key and value for the next value of the hash.
Entries are returned in an unpredictable order.
After all values have been returned, a null array is returned.
The next call to each restarts iteration.
exists expr£ Checks if the specified key exists in its hash array.
grep expr, list
grep block list
Evaluates expr or block for each element of the list, locally setting $_ to refer to the element.
Modifying $_ will modify the corresponding element from list.
Returns the array of elements from list for which expr returned true.
join expr, list Joins the separate strings of list into a single string with fields separated by the value of expr, and
returns the string.
keys %HASH Returns an array of the keys of HASH.
map expr, list
map BLOCK LIST
Evaluates expr or block for each element of the list,
locally setting $_ to refer to the element.
Modifying $_ will modify the corresponding element from list. Returns the list of results.
pop @ARRAY Pops off and returns the last value of the array.
push @ARRAY, list Pushes the values of list onto the end of the array.
reverse list In array context, returns the list in reverse order. In scalar context: returns the first element of list with bytes reversed.
scalar @ARRAY Returns the number of elements in the array.
scalar %HASH Returns a true value if the hash has elements defined.
shift [ @ARRAY ] Shifts the first value of the array off and returns it, shortening the array by 1 and moving everything down. If @ARRAY is omitted, shifts @ARGV in main and @_ in subroutines.
sort [ SUBROUTINE ] list Sorts the list and returns the sorted array value. SUBROUTINE, if specified, must return less than zero, zero, or greater than zero, depending on how the elements of the array (available to the routine as $a and $b) are to be ordered. SUBROUTINE may be the name of a user-defined routine, or a block.
splice @ARRAY, offset [ , LENGTH [ , list ] ] Removes the elements of @ARRAY designated by offset and LENGTH, and replaces them with list (if specified). Returns the elements removed.
split [ pattern [ , expr£ [ , LIMIT ] ] ] Splits a string into an array of strings, and returns it. If LIMIT is specified, splits into at most that number of fields. If pattern is also omitted, splits at the whitespace. If not in array context, returns number of fields and splits to @_. See also Search and Replace.
unshift @ARRAY, list Prepends list to the front of the array, and returns the number of elements in the new array.
values %HASH Returns a normal array consisting of all the values of the named hash.

Contents

Regular Expressions

Each character matches itself, except + ? . * ^ $ ( ) [ ] { } | \.
The special meaning of these characters is escaped using a \.

Quantified subpatterns match as many times as possible.
When followed with a ? they match the minimum number of times.

These are the quantifiers:

. matches any character, but not a newline unless it is a single-line match (see m//s).
() groups a series of pattern elements to a single element.
^ matches the beginning of the target.
In multiline mode (see m//m) also matches after every newline character.
$ matches the end of the line.
In multiline mode also matches before every newline character.
[] denotes a class of characters to match.
alpha alphabetical [A-Za-z]
alnum alphanumeric character. [A-Za-z0-9]
ascii character in the ASCII character set.
blank equal to a space or a horizontal tab ("\t"). GNU extension,
cntrl control character.
digit decimal digit ("[0-9]"), equivalent to "\d".
graph printable , i.e. graphic. excludes space.
print printable ,including a space
punct graphical excluding "word" characters. Note [5].
space whitespace . "\s" plus the vertical tab ("\cK").
lower [a-z]
upper [A-Z]
word [A-Za-z0-9_], equivalent to \w Perl extension
xdigit hexadecimal digit [0-9a-fA-F]
[^] negates the class.
(||) matches one of the alternatives.
(?# comment )
(?: REGEXP ) does not make back-references.
(?= REGEXP ) Zero width positive look-ahead assertion.
(?! REGEXP ) Zero width negative look-ahead assertion.
(? MODIFIER ) Embedded pattern-match modifier. MODIFIER can be one or more of i, m, s, or x.
  • i igore case
  • x extension
+ matches the preceding pattern element one or more times.
? matches zero or one times. i.e. not more than one.
* matches zero or more times.
{N,M} at least N and no more than M matchs ( do not escape the { as with a command like grep)
{N}means exactly N times
{N,} at least N times.

A \ escapes special meaning of the following character if non-alphanumeric,
A \ Introduces special usage for:
\w matches alphanumeric, including _, \W matches non-alphanumeric.
\s matches whitespace, \S matches non-whitespace.
\d matches digit, \D matches non-digit.
\A        \Z matches the beginning of the string, \Z matches the end.
\bmatches word boundaries, \B matches non-boundaries.
\GGo on where the previous m//g search left off.
\nNewline
\rReturn
\fFormfeed
\tTab
\w, \s and \d may be used within character classes, \b denotes backspace in this context.

Back-references:
\1\9 refer to matched subexpressions, grouped with (), inside the match.
\10 and up can also be used if the pattern matches that many subexpressions.

Variables local to the current block:
$` string preceding
$& string matched by the last successful pattern match.
$' string following
$+ last bracket matched by the last search pattern.
$1…$9…  
$10… and up (only available if Contain subpatterns from the corresponding sets of parentheses in the last pattern successfully matched.)
match contained that many subpatterns.

With modifier x, whitespace can be used in the patterns for readability purposes.

Contents

Search (Match) and Replace

[expr =~ ] [m] /pattern/
         [g][i][m][o][s][x]
Matches expr (default: $_) for pattern.
Leading m permits use of alternate of delimiters.
In array context,
   an array is returned consisting of the subexpressions
matched by the parentheses in the pattern,
  • g global matches as many times as possible
  • i ignores case
  • o intreprets $variables only once.
  • m treats the string as multiple lines
  • s treats the string as a single line
  • x allows for regular expression extensions. (ignore whitespace, allow # comments)

If pattern is empty, the most recent pattern from a previous match or replacement is used.
With g the match can be used as an iterator in scalar context.
pos scalar Returns the position where the last m/…/g search left off

?pattern?

matches only once between calls to the reset operator.

[$var =~ ] s/pattern/subs/
     [e][g][i][m][o][s][x]
substitues subs for pattern in $var.
Returns the number of substitutions or false.
  • e evaluates subs as a Perl expression
  • g replaces all occurrences of pattern
Almost any delimiter may replace the slashes (helpful if strings contain slashes, using | looks nice ed )
If ' (apostrophes) are delimiters, no interpretation of $variables.
If bracketing delimiters ( ( ), [ ], { }, < > ) are used,
   pattern
and subs may have their own delimiters,
   For example: $ary2fun =~s(@arrayn[.*])[functn()].
If pattern is empty, the most recent pattern from a previous match or replacement is used.

for example:
$x= 'xyz1aaa788899ccc' ;
$x =~ s/xyz([[:digit:]])aaa(.*)ccc/DIGITS ARE $1 $2/;
print "$x \n";
DIGITS ARE 1 788899


[$var =~] tr/chars/replchars/         [c][d][s] Translates all occurrences of chars to the corresponding character in replchars.
y may be used instead of tr.
Returns the number of characters replaced.
  • c complements the SEARCHLIST
  • d deletes all characters found in SEARCHLIST that do not have a corresponding character in replchars
  • s squeezes all sequences of characters that are translated into the same target character into one occurrence of this character.

for scalar. May be assigned to.

study $var£ Study the scalar variable $var in anticipation of performing many pattern matches on its contents before the variable is next modified.

Contents

File Test Operators

These unary operators takes one argument (or $_), filename or filehandle.
If the special argument _ (underscore) is passed, information is from the preceding test or stat .

-r -w -x  readable/writable/executable by effective uid/gid.
-R -W -X readable/writable/executable by real uid/gid.
-o -O owned by effective/real uid.
-e -z exists/has zero size.
-s exists and has non-zero size. Returns the size.
-f -d a plain file/ directory.
-l -S -p a symbolic link/ socket/ named pipe (FIFO).
-b -c a block/character special file.
-u -g -k setuid/setgid/sticky bit set.
-t filehandle (STDIN by default) is opened to a tty.
-T -B text/non-text (binary) file. Return true on a null file, or a file at EOF when testing a filehandle.
-M -A -C File modification / access / inode-change time. Measured in days. Value returned reflects the file age at the time the script started. See also $^T Special Variables.

Contents

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.
chown listChanges the owner and group of a list of files. The first two elements of the list must be the numerical uid and gid.
truncate file,size Truncates file tosize. file may be a filename or a filehandle.
mkdir DIR, MODE makes a directory with given permissions.(MODE) Sets $!
rmdir filename£removes the directory if it is empty. Sets $!
stat file Returns: ($dev, $ino, $mode, $nlink, $uid, $gid, $rdev,
           $size, $atime, $mtime, $ctime, $blksize, $blocks).
lstat file Like stat, but does not traverse a final symbolic link.
file can be a filehandle, an expression evaluating to a filename, or _ to refer to the last file test operation or stat call. Returns a null list if the stat fails.
rename oldname,newname
link,
symlink
oldfile, newfile
see ln
readlink expr£Returns the value of a symbolic link.
unlink list Deletes a list of files.
utime list Changes the access and modification times. The first two elements of the list must be the numerical access and modification times.

Contents

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 the name of a filehandle to be used.
<filehandle> In scalar context, reads a single line from the file opened on filehandle. In array context, reads the whole file.
< > Reads from the input stream formed by the files specified in @ARGV, or standard input
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).
close filehandle Closes the file or pipe associated with the filehandle.
dbmopen %HASH, Deprecated, use tie instead.
dbmclose %HASH Deprecated, use untie 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, $var Implements the fcntl(2) function. This function has non-standard return values.
fileno filehandle Returns the file descriptor for a given (open) file.
flock filehandle, operation Calls flock on the file. operation sum of 1 (shared), 2 (exclusive), 4 (non-blocking), or 8 (unlock).
getc [ filehandle ] Yields the next character from the file, or an empty string on end of file. If filehandle is omitted, reads from STDIN.
ioctl filehandle, FUNCTION, $var Performs >ioctl(2) on the file. This function has non-standard return values.
open filehandle [ , filename ] Opens a file and associates it with filehandle. If filename is omitted, the scalar variable of the same name as the filehandle must contain the filename.
The following filename conventions apply when opening a file.
file open file for input. Also "<file.
>file open file for output, creating it if necessary.
>>file open file in append mode.
+<file open file with read/write access (file must exist).
+>file open file with read/write access (file truncated).
|CMD opens a pipe to command CMD; forks if CMD is -.
CMD| opens a pipe from command CMD; forks if CMD is -.
file may be &FILEHND in which case the new filehandle is connected to the (previously opened) filehandle FILEHND. If it is &=N, file 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 [ filehandle ] [ list£ ] Equivalent to print filehandle sprintf list.
printf[([filehandle] list£)] Equivalent to print filehandle sprintf(list).
read filehandle, $var, LENGTH [ , offset ] Reads LENGTH binary bytes from the file into the variable at offset. Returns number of bytes actually read.
seek filehandle, POSITION, WHENCE Arbitarily positions the file. Returns true if successful.
select [ filehandle ] Returns the currently selected filehandle. Sets the current default filehandle for output operations if filehandle is supplied.
select RBITS, WBITS, NBITS, TIMEOUT Performs a select(2) system call with the same parameters.
sprintf FORMAT, list Returns a string formatted by (almost all of) the usual printf(3) conventions.
sysread filehandle, $var, LENGTH [ , offset ] Reads LENGTH bytes into $var at offset.
syswrite filehandle, SCALAR, LENGTH [ , offset ] Writes LENGTH bytes from SCALAR at offset.
tell [ filehandle ] Returns the current file position for the file. If filename is omitted, assumes the file last read.
write [ filehandle ] Writes a formatted record to the specified file, using the format associated with that file.

Contents

Formats

formline PICTURE, list
Formats list according to PICTURE and accumulates the result into $^A.

write [ filehandle ]
Writes a formatted record to the specified file, using the format associated with that file.

Formats are defined as:

FORMLIST pictures the lines, and contains the arguments which will give values to the fields in the lines. NAME defaults STDOUT

Picture fields are:

Use ^ instead of @ for multiline block filling.
Use ~ at the beginning of a line to suppress unwanted empty lines.
Use ~~ at the beginning of a line to have this format line repeated until all fields are exhausted.
Use $- to zero to force a page break on the next write.
See $^, $~, $^A, $^F, $- and $= Special Variables.

Contents

Directory Reading Routines

opendir DIRHANDLE, DIRNAME   Opens a directory on the handle specified.
closedir DIRHANDLE Closes a directory opened by opendir.
readdir DIRHANDLE Returns the next entry (or an array of entries) from the directory.
rewinddir DIRHANDLE Positions the directory to the beginning.
seekdir DIRHANDLE, pos Sets position for readdir on the directory.
telldir DIRHANDLE Returns the position in the directory.

Contents

System Interaction

alarm secs Schedules a SIGALRM to be delivered after secs seconds.
chdir [ expr ] Changes the working directory. Uses $ENV{"HOME"} or $ENV{"LOGNAME"} if expr is omitted.
chroot filename£ Changes the root directory for the process and its children.
die [ list ] Output list at line n to STDERR and exits with the current value of $! (errno).
If $! is 0, exits with the value of ($? >> 8).
255 If ($? >> 8) is 0.
list defaults to "Died".
warn [ list ] Output list at programName line # on STDERR defaults "Warning: something's wrong".
exec list Executes the system command in list; does not return.
system list Executes the system command in list as exec list
except that a fork is performed first, and the parent process waits for the child process to complete.
syscall util, arg1, …
exit [ expr ] Exits immediately with the value of expr, which defaults to 0 (zero).
9 if the compilation failed.
Calls END routines and object destructors before exiting.
fork Does a fork(2) system call. Returns the process ID of the child to the parent process and zero to the child process.
getlogin Returns the current login name as known by the system.
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.
getpriority which, who Returns the current priority for a process, process group, or user.
glob pat Returns a list of filenames that match the shell pattern PAT.
kill list Sends a signal to a list of processes.
The first element of the list must be the signal to send (either numeric, or its name as a string).
setpgrp PID, PGRP Sets the process group for the PID (0 means the current process).
setpriority WHICH, WHO, PRIORITY Sets the current priority for a process, process group, or a user.
sleep [ secs ] if no argument, waits for signal. Returns seconds actually slept.( usleep()
times Returns a 4-element array (0: $user, 1: $system, 2: $cuser, 3: $csystem)
user and system times, in seconds, for this process and the children of this process.
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 $? ( $? is NOT the return of operations like s// (substitute).
waitpid PID, FLAGS Performs the same function as the corresponding system call.

Contents

Networking

accept NEWSOCKET, GENERICSOCKET Accepts a new socket.
bind SOCKET, NAME Binds the NAME to the SOCKET.
connect SOCKET, NAME Connects the NAME to the SOCKET.
getpeername 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.
recv SOCKET, SCALAR, LENGTH, FLAGS Receives a message on SOCKET.
send SOCKET, MSG, FLAGS [ , TO ] Sends a message on the SOCKET.
setsockopt SOCKET, LEVEL, OPTNAME, OPTVAL Sets the requested socket option.
shutdown SOCKET, HOW Shuts down a SOCKET.
socket SOCKET, DOMAIN, TYPE, PROTOCOL Creates a SOCKET in DOMAIN with TYPE and PROTOCOL.
socketpair SOCKET1, SOCKET2, DOMAIN, TYPE, PROTOCOL  Creates a pair of bidirectional sockets.

Contents

System V IPC

You need to require "sys/ipc.ph" before you can use the symbolic names of the operations.

msgctl ID, CMD, ARGS Calls msgctl(2). If CMD is &IPC_STAT then ARGS must be a variable.
msgget KEY, FLAGS Creates a message queue for KEY. Returns the message queue identifier.
msgsnd ID, MSG, FLAGS Sends MSG to queue ID.
msgrcv ID, $var,size, TYPE, FLAGS Receives a message from queue ID into var.
semctl ID, SEMNUM, CMD, arg Calls semctl(2). If CMD is &IPC_STAT of &GETALL then arg must be a variable.
semget KEY, NSEMS,size, FLAGS Creates a set of semaphores for KEY. Returns the message semaphore identifier.
semop KEY,Performs semaphore operations.
shmctl ID, CMD, arg Calls shmctl(2). If CMD is &IPC_STAT then arg must be a variable.
shmget KEY,size, FLAGS Creates shared memory. Returns the shared memory segment identifier.
shmread ID, $var, pos,size Reads at mostsize bytes of the contents of shared memory segment ID starting at offset pos into var.
shmwrite ID, STRING, pos,size Writes at mostsize bytes of STRING into the contents of shared memory segment ID at offset pos.

Contents

Miscellaneous

defined expr Tests whether the lvalue expr has an value.
undef [ lvalue ] Undefines the lvalue. Always returns the undefined value.
do filename Executes filename as a Perl script. See also require Subroutines, Packages and Modules.
dump [ label ] core dump, contiune at label.
eval { expr ;}   Executes the code between { and }. Traps runtime errors as described with eval(expr), in the section String Functions.
local variable
local ( list ) Creates a scope for the listed variables local to the enclosing block, subroutine or eval.
my variable
my ( list ) Creates a scope for the listed variables lexically local to the enclosing block, subroutine or eval.
ref expr£ Returns a true value if expr is a reference. Returns the package name if expr has been blessed into a package.
reset [ llll ] Resets ?? searches so that they work again.
llll is a list of single letters.
All variables and arrays beginning with one of those letters are reset to their pristine state.
Only affects the current package.
scalar expr Evaluates expr in scalar context.
wantarray Returns true if the current context expects an array value.

Contents

Information from System Files

passwd returns ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell)
getpwent Gets next user information.
getpwnam NAME by name.
getpwuid UID by user ID.
endpwent Ends lookup processing.
setpwent Resets lookup
 
group returns ($name, $passwd, $gid, $members).
getgrgid GID by group ID
getgrnam NAME by name
getgrent Gets next
setgrent Resets lookup
endgrent Ends lookup
 
hosts returns ($name, $aliases, $addrtype, $length, @addrs).
gethostbyaddr ADDR, ADDRTYPE Gets information by IP address.
gethostbyname NAME Gets information by hostname.
gethostent Gets next host information.
sethostent STAYOPEN Resets lookup processing.
endhostent Ends lookup processing.
 
networks returns ($name, $aliases, $addrtype, $net).
getnetbyaddr ADDR, TYPE Gets information by address and type.
getnetbyname NAME Gets information by network name.
getnetent Gets next network information.
setnetent STAYOPEN Resets lookup processing.
endnetent Ends lookup processing.
 
services returns ($name, $aliases, $port, $proto).
getservbyname NAME, PROTO Gets information by service name.
getservbyport PORT, PROTO Gets information by service port.
getservent Gets next service information.
setservent STAYOPEN Resets lookup processing.
endservent Ends lookup processing.
 
protocols returns ($name, $aliases, $proto).
getprotobyname NAME Gets information by protocol name.
getprotobynumber number Gets information by protocol number.
getprotoent Gets next protocol information.
setprotoent STAYOPEN Resets lookup processing.
endprotoent Ends lookup processing.

Contents

Special Variables

Include use English; to use variable names (some match those keywords in awk
global and should be localized in subroutines:
@_ @ARG parameters passed to subroutine
$! errno when used in a numeric context
error string when used in a string context
$@ error message from the last eval or do expr command.
$. current input line number of the last filehandle that was read.
$/ $INPUT_RECORD_SEPARATOR aka $RS newline by default. May be multicharacter.
$\ $OUTPUT_RECORD_SEPARATOR for print
$, Output Field Separator ""
$" $LIST_SEPERATOR joins elements of arrays when interpolated in strings. Default space
example: @a[0]='aa'; @a[1]='bb';
          $"='+';
          print "@a";
          aa+bb
$; $SUBSCRIPT_SEPARATOR $SUBSEP for multidimensional array emulation. Default \034, x'1C' ASCII FieldSeperator
$? status returned by the last `` command, pipe close or system operator.
 
$: set of characters after which a string may be broken to fill continuation fields (starting with ^) in a format.
@F fields of line read in autosplit mode -a
$0 $PROGRAM_NAME being executed. May be assigned to for display in ps
$1,… (matches) in =~ m/
%ENV hash of ENVIRONMENT variables, setting on is seen by forked children
$$ $PROCESS_ID $PIDof the currently executing program. Altered (in child process) by fork.
$< $REAL_USER_ID $UID
$> $EFFECTIVE_USER_ID $EUID
$( $REAL_GROUP_ID $GID
$) $EFFECTIVE_GROUP_ID $EGID
$^A accumulator for formline and write operations.
$^F highest system file descriptor, ordinarily 2.
$^I In-place edit extension as passed to Perl using -i.
$^L Formfeed character used in formats.
$^T time (as delivered by time) when the program started. used by file test operators -M, -A and -C. ( hard to type in if ^T is the stty int key )
$] perl version number, e.g., 5.001.
$^D debug flags as passed to perl using -D.
$^W value of the -w option as passed to Perl.
$^X name by which the currently executing program was invoked.
$^P Internal debugging flag.
$[ index of the first element in an array, and of the first character in a substring. Default is 0. Deprecated.
$# output format for printed numbers. Deprecated.
$* Set to 1 to do multiline matching within strings. Deprecated, see m and s modifiers Search and Replace.
 
context dependent and need not be localized:
$% current page number of the currently selected output channel.
$= page length of the current output channel. Default is 60 lines.
$- number of lines remaining on the page.
$~ name of the current report format.
$^ name of the current top-of-page format.
$| If set to nonzero, flushs after write or print on currently selected output channel. Default is 0.
$ARGV name of the current file when reading from <>.
 
local to the current block:
$& string matched by the last successful pattern match.
$` string preceding ""
$' string following ""
$+ last bracket matched by the last search pattern.
$1$9…   Contain subpatterns from the corresponding sets of parentheses in the last pattern successfully matched.
$10… and up are only available if match contained that many subpatterns.

Contents

Special Arrays

@ARGV command-line arguments for the script (not including the command name).
@EXPORT Names the methods a package exports by default.
@EXPORT_OK  Names the methods a package can export upon explicit request.
@INC directories to search for do filename and require
@ISA base classes of a package.
@_ Parameter array for subroutines. Also used by split if not in array context.
%ENV current environment.
%INC List of files that have been included with require or do.
%OVERLOAD used to overload operators in a package.
%SIG Used to set signal handlers

Contents

Environment Variables

Perl uses the following environment variables.

HOME default for chdir
LOGDIR default for chdir without argument and HOME is not set.
PATH Used for subprocesses, and the Perl script with -S
PERL5LIB  colon-separated list of directories to search for library files before looking in the standard library and the current directory.
PERL5DB The command to get the debugger code. Default: BEGIN { require 'perl5db.pl' }.
PERLLIB Used instead of PERL5LIB if the latter is not defined.
TOC

The Perl Debugger

Invoked with perl -d. DGG's Version

h Prints out help.
T Prints a stack trace.
s Single steps.
n Single steps around subroutine call.
RETURN key Repeats last s or n.
r current subroutine.
c [ LINE ] Continues (until LINE, or another breakpoint, or exit).
p expr outputs expr.
l [ RANGE ] Lists a range of lines. RANGE may be a number, start-end, start+amount, or a subroutine name.
If RANGE is omitted, lists next window.
w Lists window around current line.
- Lists previous window.
f file Switches to file and starts listing it.
l sub the named subroutine.
S names of all subroutines.
/pattern/ Searches forward for pattern.
?pattern? Searches backward
b [ LINE [ CONDITION ] ]   Sets breakpoint at LINE; default is the current line.
b sub [ CONDITION ] Sets breakpoint at the subroutine.
d [ LINE ] Deletes breakpoint at the given line.
D Deletes all breakpoints.
L Lists lines that have breakpoints or actions.
a LINE COMMAND Sets an action for line.
A Deletes all line actions.
< COMMAND Sets an action to be executed before every debugger prompt.
> COMMAND Sets an action to be executed before every s, c or n command.
V [ PACKAGE [ VARS ] ]   Lists all variables in a package. Default package is main.
X [ VARS ] Like V, but assumes current package.
! [ [-]number ] Re-executes a command. Default is the previous command.
H [ -number ] Displays the last -number commands of more than one letter.
t Toggles trace mode.
= [ ALIAS VALUE ] Sets alias, or lists current aliases.
q Quits. You may also use your EOF key character.
COMMAND Executes COMMAND as a Perl statement.

Contents

Command-Line Options

-w prints warnings about possible spelling errors and other error-prone constructs in the script.
-d runs the script under the debugger.
Use -de 0 to start the debugger without a script
-D number sets Debugging flags.
-F REGEXP specifies a regular expression to split on
-p assumes an input loop around script. Lines are printed.
-n assumes an input loop around script. Lines are not printed.
-a autosplit mode when used with -n or -p. Splits to @F.
-c checks syntax but does not execute.
-e COMMANDLINE    enter a single line of script.
Multiple -e commands may be given to build up a multiline script. if -a is in effect.
-iEXT files processed by the < > construct are to be edited in place.
-s interprets -xxx on the command line as a switch and sets the corresponding variable $xxx in the script.
-S Search for the script using the PATH environment variable
-T Taint checking.
-u dumps core after compiling the script. To be used with >undump.
-U allows perl to perform Unsafe operations.
-v prints the version and patchlevel of your Perl executable.
-x [DIR] extracts Perl program from input stream. If DIR is specified, CDs to this directory before running the program.
-0VAL (zero) Designates an initial value for the Record Separator $/. See also -l
-l [OCTNUM] enables automatic line-end processing, e.g., -l013 ( ).
-P runs the C Preprocessor on the script before compilation by Perl.
-IDIR with -P, tells the C preprocessor where to look for Include files. The directory is prepended to @INC.
Last updated 22 March 2001
[Links updated 7 September 2003]

Text copyright © 1996 Johan Vromans
HTML copyright © 1996-2003 Rex Swain
Adapted from Rex Swain's HTMLified with minor modifications by Dennis German.
Reports of errors or omissions appreciated

See also perldoc.perl.org