=head1 DESCRIPTION
=head2 Variable names
+X<variable, name> X<variable name> X<data type> X<type>
Perl has three built-in data types: scalars, arrays of scalars, and
associative arrays of scalars, known as "hashes". A scalar is a
for a simple identifier, an expression that produces a reference
to the value at runtime. This is described in more detail below
and in L<perlref>.
+X<identifier>
Perl also has its own built-in variables whose names don't follow
these rules. They have strange names so they don't accidentally
In addition, several special variables that provide windows into
the inner working of Perl have names containing punctuation characters
and control characters. These are documented in L<perlvar>.
+X<variable, built-in>
Scalar values are always named with '$', even when referring to a
scalar that is part of an array or a hash. The '$' symbol works
semantically like the English word "the" in that it indicates a
single value is expected.
+X<scalar>
$days # the simple scalar value "days"
$days[28] # the 29th element of array @days
Entire arrays (and slices of arrays and hashes) are denoted by '@',
which works much like the word "these" or "those" does in English,
in that it indicates multiple values are expected.
+X<array>
@days # ($days[0], $days[1],... $days[n])
@days[3,4,5] # same as ($days[3],$days[4],$days[5])
@days{'a','c'} # same as ($days{'a'},$days{'c'})
Entire hashes are denoted by '%':
+X<hash>
%days # (key1, val1, key2, val2 ...)
and @foo are two different variables. It also means that C<$foo[1]>
is a part of @foo, not a part of $foo. This may seem a bit weird,
but that's okay, because it is weird.
+X<namespace>
Because variable references always start with '$', '@', or '%', the
"reserved" words aren't in fact reserved with respect to variable
from conflict with future reserved words. Case I<is> significant--"FOO",
"Foo", and "foo" are all different names. Names that start with a
letter or underscore may also contain digits and underscores.
+X<identifier, case sensitivity>
+X<case>
It is possible to replace such an alphanumeric name with an expression
that returns a reference to the appropriate type. For a description
id.)
=head2 Context
+X<context> X<scalar context> X<list context>
The interpretation of operations and values in Perl sometimes depends
on the requirements of the context around the operation or value.
context.
=head2 Scalar values
+X<scalar> X<number> X<string> X<reference>
All data in Perl is a scalar, an array of scalars, or a hash of
scalars. A scalar may contain one single value in any of three
the null string or the number 0 (or its string equivalent, "0"). The
Boolean context is just a special kind of scalar context where no
conversion to a string or a number is ever performed.
+X<boolean> X<bool> X<true> X<false> X<truth>
There are actually two varieties of null strings (sometimes referred
to as "empty" strings), a defined one and an undefined one. The
use the defined() operator to determine whether a scalar value is
defined (this has no meaning on arrays or hashes), and the undef()
operator to produce an undefined value.
+X<defined> X<undefined> X<undef> X<null> X<string, null>
To find out whether a given string is a valid non-zero number, it's
sometimes enough to test it against both numeric 0 and also lexical
an array that was previously shortened does not recover values
that were in those elements. (It used to do so in Perl 4, but we
had to break this to make sure destructors were called when expected.)
+X<$#> X<array, length>
You can also gain some minuscule measure of efficiency by pre-extending
an array that is going to get big. You can also extend an array
the last value, like the C comma operator, nor of built-in functions,
which return whatever they feel like returning.) The following is
always true:
+X<array, length>
scalar(@whatever) == $#whatever - $[ + 1;
the value of C<$[> no longer need to worry about whether another
file changed its value. (In other words, use of C<$[> is deprecated.)
So in general you can assume that
+X<$[>
scalar(@whatever) == $#whatever + 1;
10,000 of your items. This isn't supposed to happen. If a tied hash
is evaluated in scalar context, a fatal error will result, since this
bucket usage information is currently not available for tied hashes.
+X<hash, scalar context> X<hash, bucket> X<bucket>
You can preallocate space for a hash by assigning to the keys() function.
This rounds up the allocated buckets to the next power of two:
keys(%users) = 1000; # allocate 1024 buckets
=head2 Scalar value constructors
+X<scalar, literal> X<scalar, constant>
Numeric literals are specified in any of the following floating point or
integer formats:
between digits for legibility. You could, for example, group binary
digits by threes (as for a Unix-style mode argument such as 0b110_100_100)
or by fours (to represent nibbles, as in 0b1010_0110) or in other groups.
+X<number, literal>
String literals are usually delimited by either single or double
quotes. They work much like quotes in the standard Unix shells:
C<\\>). The usual C-style backslash rules apply for making
characters such as newline, tab, etc., as well as some more exotic
forms. See L<perlop/"Quote and Quote-like Operators"> for a list.
+X<string, literal>
Hexadecimal, octal, or binary, representations in string literals
(e.g. '0xff') are not automatically converted to their integer
names beginning with $ or @, followed by an optional bracketed
expression as a subscript.) The following code segment prints out "The
price is $Z<>100."
+X<interpolation>
$Price = '$100'; # not interpolated
print "The price is $Price.\n"; # interpolated
this when interpolating a variable into a string to separate the
variable name from a following double-colon or an apostrophe, since
these would be otherwise treated as a package separator:
+X<interpolation>
$who = "Larry";
print PASSWD "${who}::0:0:Superuser:/:/bin/perl\n";
equivalent to C<$version{2}++>, not to C<$version{'2.0'}++>.
=head3 Version Strings
+X<version string> X<vstring> X<v-string>
B<Note:> Version Strings (v-strings) have been deprecated. They will
be removed in some future release after Perl 5.8.1. The marginal
be v-strings always.
=head3 Special Literals
+X<special literal> X<__END__> X<__DATA__> X<END> X<DATA>
+X<end> X<data> X<^D> X<^Z>
The special literals __FILE__, __LINE__, and __PACKAGE__
represent the current filename, line number, and package name at that
will not be interpolated into strings. If there is no current package
(due to an empty C<package;> directive), __PACKAGE__ is the undefined
value.
+X<__FILE__> X<__LINE__> X<__PACKAGE__> X<line> X<file> X<package>
The two control characters ^D and ^Z, and the tokens __END__ and __DATA__
may be used to indicate the logical end of the script before the actual
__DATA__ (or __END__) token has not yet been seen.
=head3 Barewords
+X<bareword>
A word that has no other interpretation in the grammar will
be treated as if it were a quoted string. These are known as
by saying C<no strict 'subs'>.
=head3 Array Joining Delimiter
+X<array, interpolation> X<interpolation, array> X<$">
Arrays and slices are interpolated into double-quoted strings
by joining the elements with the delimiter specified in the C<$">
L<perlop/Quote and Quote-like Operators>.
=head2 List value constructors
+X<list>
List values are denoted by separating individual values by commas
(and enclosing the list in parentheses where precedence requires it):
print "Darwin's First Name is ", $scientists{"Darwin"}, "\n";
=head2 Slices
+X<slice> X<array, slice> X<hash, slice>
A common way to access an array or a hash is one scalar element at a
time. You can also subscript a list to get a single element from it.
scalar) or a plural one (a list).
=head2 Typeglobs and Filehandles
+X<typeglob> X<filehandle> X<*>
Perl uses an internal type called a I<typeglob> to hold an entire
symbol table entry. The type prefix of a typeglob is a C<*>, because
=head1 NAME
+X<debug> X<debugger>
perldebug - Perl debugging
variables, etc. This is so convenient that you often fire up
the debugger all by itself just to test out Perl constructs
interactively to see what they do. For example:
+X<-d>
$ perl -d -e 42
=over 12
=item h
+X<debugger command, h>
Prints out a summary help message
=item p expr
+X<debugger command, p>
Same as C<print {$DB::OUT} expr> in the current package. In particular,
because this is just Perl's own C<print> function, this means that nested
where STDOUT may be redirected to.
=item x [maxdepth] expr
+X<debugger command, x>
Evaluates its expression in list context and dumps out the result in a
pretty-printed fashion. Nested data structures are printed out
temporarily set to I<N>.
=item V [pkg [vars]]
+X<debugger command, V>
Display all (or some) variables in package (defaulting to C<main>)
using a data pretty-printer (hashes show their keys and values so
This is similar to calling the C<x> command on each applicable var.
=item X [vars]
+X<debugger command, X>
Same as C<V currentpackage [vars]>.
=item y [level [vars]]
+X<debugger command, y>
Display all (or some) lexical variables (mnemonic: C<mY> variables)
in the current scope or I<level> scopes higher. You can limit the
controlled by the same options.
=item T
+X<debugger command, T> X<backtrace> X<stack, backtrace>
Produce a stack backtrace. See below for details on its output.
=item s [expr]
+X<debugger command, s> X<step>
Single step. Executes until the beginning of another
statement, descending into subroutine calls. If an expression is
supplied that includes function calls, it too will be single-stepped.
=item n [expr]
+X<debugger command, n>
Next. Executes over subroutine calls, until the beginning
of the next statement. If an expression is supplied that includes
each statement.
=item r
+X<debugger command, r>
Continue until the return from the current subroutine.
Dump the return value if the C<PrintRet> option is set (default).
Repeat last C<n> or C<s> command.
=item c [line|sub]
+X<debugger command, c>
Continue, optionally inserting a one-time-only breakpoint
at the specified line or subroutine.
=item l
+X<debugger command, l>
List next window of lines.
be a variable that contains a code reference.
=item -
+X<debugger command, ->
List previous window of lines.
=item v [line]
+X<debugger command, v>
View a few lines of code around the current line.
=item .
+X<debugger command, .>
Return the internal debugger pointer to the line last
executed, and print out that line.
=item f filename
+X<debugger command, f>
Switch to viewing a different file or C<eval> statement. If I<filename>
is not a full pathname found in the values of %INC, it is considered
The search is case-insensitive by default.
=item L [abw]
+X<debugger command, L>
List (default all) actions, breakpoints and watch expressions
=item S [[!]regex]
+X<debugger command, S>
List subroutine names [not] matching the regex.
=item t
+X<debugger command, t>
Toggle trace mode (see also the C<AutoTrace> option).
=item t expr
+X<debugger command, t>
Trace through execution of C<expr>.
See L<perldebguts/"Frame Listing Output Examples"> for examples.
=item b
+X<breakpoint>
+X<debugger command, b>
Sets breakpoint on current line
=item b [line] [condition]
+X<breakpoint>
+X<debugger command, b>
Set a breakpoint before the given line. If a condition
is specified, it's evaluated each time the statement is reached: a
b 33 /pattern/i
=item b subname [condition]
+X<breakpoint>
+X<debugger command, b>
Set a breakpoint before the first line of the named subroutine. I<subname> may
be a variable containing a code reference (in this case I<condition>
is not supported).
=item b postpone subname [condition]
+X<breakpoint>
+X<debugger command, b>
Set a breakpoint at first line of subroutine after it is compiled.
=item b load filename
+X<breakpoint>
+X<debugger command, b>
Set a breakpoint before the first executed line of the I<filename>,
which should be a full pathname found amongst the %INC values.
=item b compile subname
+X<breakpoint>
+X<debugger command, b>
Sets a breakpoint before the first statement executed after the specified
subroutine is compiled.
=item B line
+X<breakpoint>
+X<debugger command, B>
Delete a breakpoint from the specified I<line>.
=item B *
+X<breakpoint>
+X<debugger command, B>
Delete all installed breakpoints.
=item a [line] command
+X<debugger command, a>
Set an action to be done before the line is executed. If I<line> is
omitted, set an action on the line about to be executed.
a 53 print "DB FOUND $foo\n"
=item A line
+X<debugger command, A>
Delete an action from the specified line.
=item A *
+X<debugger command, A>
Delete all installed actions.
=item w expr
+X<debugger command, w>
Add a global watch-expression. We hope you know what one of these
is, because they're supposed to be obvious.
=item W expr
+X<debugger command, W>
Delete watch-expression
=item W *
+X<debugger command, W>
Delete all watch-expressions.
=item o
+X<debugger command, o>
Display all options
=item o booloption ...
+X<debugger command, o>
Set each listed Boolean option to the value C<1>.
=item o anyoption? ...
+X<debugger command, o>
Print out the value of one or more options.
=item o option=value ...
+X<debugger command, o>
Set the value of one or more options. If the value has internal
whitespace, it should be quoted. For example, you could set C<o
for a list of these.
=item < ?
+X<< debugger command, < >>
List out all pre-prompt Perl command actions.
=item < [ command ]
+X<< debugger command, < >>
Set an action (Perl command) to happen before every debugger prompt.
A multi-line command may be entered by backslashing the newlines.
=item < *
+X<< debugger command, < >>
Delete all pre-prompt Perl command actions.
=item << command
+X<< debugger command, << >>
Add an action (Perl command) to happen before every debugger prompt.
A multi-line command may be entered by backwhacking the newlines.
=item > ?
+X<< debugger command, > >>
List out post-prompt Perl command actions.
=item > command
+X<< debugger command, > >>
Set an action (Perl command) to happen after the prompt when you've
just given a command to return to executing the script. A multi-line
couldn't've guessed this by now).
=item > *
+X<< debugger command, > >>
Delete all post-prompt Perl command actions.
=item >> command
+X<<< debugger command, >> >>>
Adds an action (Perl command) to happen after the prompt when you've
just given a command to return to executing the script. A multi-line
command may be entered by backslashing the newlines.
=item { ?
+X<debugger command, {>
List out pre-prompt debugger commands.
C<do { ... }>.
=item { *
+X<debugger command, {>
Delete all pre-prompt debugger commands.
=item {{ command
+X<debugger command, {{>
Add an action (debugger command) to happen before every debugger prompt.
A multi-line command may be entered, if you can guess how: see above.
=item ! number
+X<debugger command, !>
Redo a previous command (defaults to the previous command).
=item ! -number
+X<debugger command, !>
Redo number'th previous command.
=item ! pattern
+X<debugger command, !>
Redo last command that started with pattern.
See C<o recallCommand>, too.
=item !! cmd
+X<debugger command, !!>
Run cmd in a subprocess (reads from DB::IN, writes to DB::OUT) See
C<o shellBang>, also. Note that the user's current shell (well,
information.
=item source file
+X<debugger command, source>
Read and execute debugger commands from I<file>.
I<file> may itself contain C<source> commands.
=item H -number
+X<debugger command, H>
Display last n commands. Only commands longer than one character are
listed. If I<number> is omitted, list them all.
=item q or ^D
+X<debugger command, q>
+X<debugger command, ^D>
Quit. ("quit" doesn't work for this, unless you've made an alias)
This is the only supported way to exit the debugger, though typing
if you want to step through global destruction.
=item R
+X<debugger command, R>
Restart the debugger by C<exec()>ing a new session. We try to maintain
your history across this, but internal settings and command-line options
options B<-w>, B<-I>, and B<-e>.
=item |dbcmd
+X<debugger command, |>
Run the debugger command, piping DB::OUT into your current pager.
=item ||dbcmd
+X<debugger command, ||>
Same as C<|dbcmd> but DB::OUT is temporarily C<select>ed as well.
=item = [alias value]
+X<debugger command, =>
Define a command alias, like
Perl debugger, use a leading semicolon, too.
=item m expr
+X<debugger command, m>
List which methods may be called on the result of the evaluated
expression. The expression may evaluated to a reference to a
blessed object, or to a package name.
=item M
+X<debugger command, M>
Displays all loaded modules and their versions
=item man [manpage]
+X<debugger command, man>
Despite its name, this calls your system's default documentation
viewer on the given page, or on the viewer itself if I<manpage> is
=over 12
=item C<recallCommand>, C<ShellBang>
+X<debugger option, recallCommand>
+X<debugger option, ShellBang>
The characters used to recall command or spawn shell. By
default, both are set to C<!>, which is unfortunate.
=item C<pager>
+X<debugger option, pager>
Program to use for output of pager-piped commands (those beginning
with a C<|> character.) By default, C<$ENV{PAGER}> will be used.
will not be readable when sent through the pager.
=item C<tkRunning>
+X<debugger option, tkRunning>
Run Tk while prompting (with ReadLine).
=item C<signalLevel>, C<warnLevel>, C<dieLevel>
+X<debugger option, signalLevel> X<debugger option, warnLevel>
+X<debugger option, dieLevel>
Level of verbosity. By default, the debugger leaves your exceptions
and warnings alone, because altering them can break correctly running
destroy any program that takes its exception handling seriously.
=item C<AutoTrace>
+X<debugger option, AutoTrace>
Trace mode (similar to C<t> command, but can be put into
C<PERLDB_OPTS>).
=item C<LineInfo>
+X<debugger option, LineInfo>
File or pipe to print line number info to. If it is a pipe (say,
C<|visual_perl_db>), then a short message is used. This is the
debugger.
=item C<inhibit_exit>
+X<debugger option, inhibit_exit>
If 0, allows I<stepping off> the end of the script.
=item C<PrintRet>
+X<debugger option, PrintRet>
Print return value after C<r> command if set (default).
=item C<ornaments>
+X<debugger option, ornaments>
Affects screen appearance of the command line (see L<Term::ReadLine>).
There is currently no way to disable these, which can render
This is considered a bug.
=item C<frame>
+X<debugger option, frame>
Affects the printing of messages upon entry and exit from subroutines. If
C<frame & 2> is false, messages are printed on entry only. (Printing
next option:
=item C<maxTraceLen>
+X<debugger option, maxTraceLen>
Length to truncate the argument list when the C<frame> option's
bit 4 is set.
=item C<windowSize>
+X<debugger option, windowSize>
Change the size of code list window (default is 10 lines).
=over 12
=item C<arrayDepth>, C<hashDepth>
+X<debugger option, arrayDepth> X<debugger option, hashDepth>
Print only first N elements ('' for all).
=item C<dumpDepth>
+X<debugger option, dumpDepth>
Limit recursion depth to N levels when dumping structures.
Negative values are interpreted as infinity. Default: infinity.
=item C<compactDump>, C<veryCompact>
+X<debugger option, compactDump> X<debugger option, veryCompact>
Change the style of array and hash output. If C<compactDump>, short array
may be printed on one line.
=item C<globPrint>
+X<debugger option, globPrint>
Whether to print contents of globs.
=item C<DumpDBFiles>
+X<debugger option, DumpDBFiles>
Dump arrays holding debugged files.
=item C<DumpPackages>
+X<debugger option, DumpPackages>
Dump symbol tables of packages.
=item C<DumpReused>
+X<debugger option, DumpReused>
Dump contents of "reused" addresses.
=item C<quote>, C<HighBit>, C<undefPrint>
+X<debugger option, quote> X<debugger option, HighBit>
+X<debugger option, undefPrint>
Change the style of string dump. The default value for C<quote>
is C<auto>; one can enable double-quotish or single-quotish format
with their high bit set are printed verbatim.
=item C<UsageOnly>
+X<debugger option, UsageOnly>
Rudimentary per-package memory usage dump. Calculates total
size of strings found in variables in the package. This does not
=over 12
=item C<TTY>
+X<debugger option, TTY>
The TTY to use for debugging I/O.
=item C<noTTY>
+X<debugger option, noTTY>
If set, the debugger goes into C<NonStop> mode and will not connect to a TTY. If
interrupted (or if control goes to the debugger via explicit setting of
possible.
=item C<ReadLine>
+X<debugger option, ReadLine>
If false, readline support in the debugger is disabled in order
to debug applications that themselves use ReadLine.
=item C<NonStop>
+X<debugger option, NonStop>
If set, the debugger goes into non-interactive mode until interrupted, or
programmatically by setting $DB::signal or $DB::single.
commands typed into the debugger.
=item Stack backtrace
+X<backtrace> X<stack, backtrace>
Here's an example of what a stack backtrace via C<T> command might
look like:
your Perl as a C programmer might.
=head2 The Perl Profiler
+X<profile> X<profiling> X<profiler>
If you wish to supply an alternative debugger for Perl to run, just
invoke your script with a colon and a package argument given to the
interpret the information in that profile.
=head1 Debugging regular expressions
+X<regular expression, debugging>
+X<regex, debugging> X<regexp, debugging>
C<use re 'debug'> enables you to see the gory details of how the Perl
regular expression engine works. In order to understand this typically
L<perldebguts/"Debugging regular expressions">.
=head1 Debugging memory usage
+X<memory usage>
Perl contains internal support for reporting its own memory usage,
but this is a fairly advanced concept that requires some understanding
=head1 NAME
+X<data structure> X<complex data structure> X<struct>
perldsc - Perl Data Structures Cookbook
these types of data structures.
=head1 REFERENCES
+X<reference> X<dereference> X<dereferencing> X<pointer>
The most important thing to understand about all data structures in Perl
-- including multidimensional arrays--is that even though they might
one-dimensional. They can hold only scalar values (meaning a string,
number, or a reference). They cannot directly contain other arrays or
hashes, but instead contain I<references> to other arrays or hashes.
+X<multidimensional array> X<array, multidimensional>
You can't use a reference to an array or hash in quite the same way that you
would a real array or hash. For C or C++ programmers unused to
memory. In Perl, you'll want to use the array constructor C<[]> or the
hash constructor C<{}> instead. Here's the right way to do the preceding
broken code fragments:
+X<[]> X<{}>
for $i (1..10) {
@array = somefunc($i);
=head1 CAVEAT ON PRECEDENCE
+X<dereference, precedence> X<dereferencing, precedence>
Speaking of things like C<@{$AoA[$i]}>, the following are actually the
same thing:
+X<< -> >>
$aref->[2][2] # clear
$$aref[2][2] # confusing
print $aref->[2][2]
=head1 DEBUGGING
+X<data structure, debugging> X<complex data structure, debugging>
+X<AoA, debugging> X<HoA, debugging> X<AoH, debugging> X<HoH, debugging>
+X<array of arrays, debugging> X<hash of arrays, debugging>
+X<array of hashes, debugging> X<hash of hashes, debugging>
Before version 5.002, the standard Perl debugger didn't do a very nice job of
printing out complex data structures. With 5.002 or above, the
types of data structures.
=head1 ARRAYS OF ARRAYS
+X<array of arrays> X<AoA>
=head2 Declaration of an ARRAY OF ARRAYS
}
=head1 HASHES OF ARRAYS
+X<hash of arrays> X<HoA>
=head2 Declaration of a HASH OF ARRAYS
}
=head1 ARRAYS OF HASHES
+X<array of hashes> X<AoH>
=head2 Declaration of an ARRAY OF HASHES
}
=head1 HASHES OF HASHES
+X<hass of hashes> X<HoH>
=head2 Declaration of a HASH OF HASHES
=head1 MORE ELABORATE RECORDS
+X<record> X<structure> X<struct>
=head2 Declaration of MORE ELABORATE RECORDS
formats, and footers.
=head2 How do I flush/unbuffer an output filehandle? Why must I do this?
+X<flush> X<buffer> X<unbuffer> X<autoflush>
Perl does not support truly unbuffered output (except
insofar as you can C<syswrite(OUT, $char, 1)>), although it
$sock->autoflush();
=head2 How do I change one line in a file/delete a line in a file/insert a line in the middle of a file/append to the beginning of a file?
+X<file, editing>
Use the Tie::File module, which is included in the standard
distribution since Perl 5.8.0.
=head2 How do I count the number of lines in a file?
+X<file, counting lines> X<lines> X<line>
One fairly efficient way is to count newlines in the file. The
following program uses a feature of tr///, as documented in L<perlop>.
This assumes no funny games with newline translations.
=head2 How can I use Perl's C<-i> option from within a program?
+X<-i> X<in-place>
C<-i> sets the value of Perl's C<$^I> variable, which in turn affects
the behavior of C<< <> >>; see L<perlrun> for more details. By
C<.c.orig> file.
=head2 How can I copy a file?
+X<copy> X<file, copy>
(contributed by brian d foy)
to the destination file as you read the original.
=head2 How do I make a temporary file name?
+X<file, temporary>
If you don't need to know the name of the file, you can use C<open()>
with C<undef> in place of the file name. The C<open()> function
}
=head2 How can I manipulate fixed-record-length files?
+X<fixed-length> X<file, fixed-length records>
The most efficient way is using L<pack()|perlfunc/"pack"> and
L<unpack()|perlfunc/"unpack">. This is faster than using
with global variables and using symbolic references.
=head2 How can I make a filehandle local to a subroutine? How do I pass filehandles between subroutines? How do I make an array of filehandles?
+X<filehandle, local> X<filehandle, passing> X<filehandle, reference>
As of perl5.6, open() autovivifies file and directory handles
as references if you pass it an uninitialized scalar variable.
check out the Symbol or IO::Handle modules.
=head2 How can I use a filehandle indirectly?
+X<filehandle, indirect>
An indirect filehandle is using something other than a symbol
in a place that a filehandle is expected. Here are ways
game doesn't help you at all here.
=head2 How can I set up a footer format to be used with write()?
+X<footer>
There's no builtin way to do this, but L<perlform> has a couple of
techniques to make it possible for the intrepid hacker.
=head2 How can I write() into a string?
+X<write, into a string>
See L<perlform/"Accessing Formatting Internals"> for an swrite() function.
=head2 How can I output my numbers with commas added?
+X<number, commify>
(contributed by brian d foy and Benjamin Goldberg)
)/$1,/xg;
=head2 How can I translate tildes (~) in a filename?
+X<tilde> X<tilde expansion>
Use the <> (glob()) operator, documented in L<perlfunc>. Older
versions of Perl require that you have a shell installed that groks
}ex;
=head2 How come when I open a file read-write it wipes it out?
+X<clobber> X<read-write> X<clobbering> X<truncate> X<truncating>
Because you're using something like this, which truncates the file and
I<then> gives you read-write access:
See also the new L<perlopentut> if you have it (new for 5.6).
=head2 Why do I sometimes get an "Argument list too long" when I use E<lt>*E<gt>?
+X<argument list too long>
The C<< <> >> operator performs a globbing operation (see above).
In Perl versions earlier than v5.6.0, the internal glob() operator forks
one that doesn't use the shell to do globbing.
=head2 Is there a leak/bug in glob()?
+X<glob>
Due to the current implementation on some operating systems, when you
use the glob() function or its angle-bracket alias in a scalar
best therefore to use glob() only in list context.
=head2 How can I open a file with a leading ">" or trailing blanks?
+X<filename, special characters>
(contributed by Brian McCauley)
open FILE, ">", ">file"; # filename is ">file"
=head2 How can I reliably rename a file?
+X<rename> X<mv> X<move> X<file, rename> X<ren>
If your operating system supports a proper mv(1) utility or its
functional equivalent, this works:
Newer versions of File::Copy export a move() function.
=head2 How can I lock a file?
+X<lock> X<file, lock> X<flock>
Perl's builtin flock() function (see L<perlfunc> for details) will call
flock(2) if that exists, fcntl(2) if it doesn't (on perl version 5.004 and
=back
=head2 Why can't I just open(FH, "E<gt>file.lock")?
+X<lock, lockfile race condition>
A common bit of code B<NOT TO USE> is this:
these tend to involve busy-wait, which is also subdesirable.
=head2 I still don't get locking. I just want to increment the number in the file. How can I do this?
+X<counter> X<file, counter>
Didn't anyone ever tell you web-page hit counters were useless?
They don't count number of hits, they're a waste of time, and they serve
If the count doesn't impress your friends, then the code might. :-)
=head2 All I want to do is append a small amount of text to the end of a file. Do I still have to use locking?
+X<append> X<file, append>
If you are on a system that correctly implements flock() and you use the
example appending code from "perldoc -f flock" everything will be OK
systems where this probability is reduced to zero.
=head2 How do I randomly update a binary file?
+X<file, binary patch>
If you're just trying to patch a binary, in many cases something as
simple as this works:
Don't forget them or you'll be quite sorry.
=head2 How do I get a file's timestamp in perl?
+X<timestamp> X<file, timestamp>
If you want to retrieve the time at which the file was last
read, written, or had its meta-data (owner, etc) changed,
for details.
=head2 How do I set a file's timestamp in perl?
+X<timestamp> X<file, timestamp>
You use the utime() function documented in L<perlfunc/utime>.
By way of example, here's a little program that copies the
the filesystems, not of utime().
=head2 How do I print to more than one file at once?
+X<print, to multiple files>
To connect one filehandle to several output filehandles,
you can use the IO::Tee or Tie::FileHandle::Multiplex modules.
for $fh (FH1, FH2, FH3) { print $fh "whatever\n" }
=head2 How can I read in an entire file all at once?
+X<slurp> X<file, slurping>
You can use the File::Slurp module to do it in one step.
and reads that many bytes into the buffer $var.
=head2 How can I read in a file by paragraphs?
+X<file, reading by paragraphs>
Use the C<$/> variable (see L<perlvar> for details). You can either
set it to C<""> to eliminate empty paragraphs (C<"abc\n\n\n\ndef">,
S<C<"fred\n \nstuff\n\n">> is one paragraph, but C<"fred\n\nstuff\n\n"> is two.
=head2 How can I read a single character from a file? From the keyboard?
+X<getc> X<file, reading one character at a time>
You can use the builtin C<getc()> function for most filehandles, but
it won't (easily) work on a terminal device. For STDIN, either use
pipes, and tty devices work, but I<not> files.
=head2 How do I do a C<tail -f> in perl?
+X<tail>
First try
There's also a File::Tail module from CPAN.
=head2 How do I dup() a filehandle in Perl?
+X<dup>
If you check L<perlfunc/open>, you'll see that several of the ways
to call open() should do the trick. For example:
Error checking, as always, has been left as an exercise for the reader.
=head2 How do I close a file descriptor by number?
+X<file, closing file descriptors>
This should rarely be necessary, as the Perl close() function is to be
used for things that Perl opened itself, even if it was a dup of a
}
=head2 Why can't I use "C:\temp\foo" in DOS paths? Why doesn't `C:\temp\foo.exe` work?
+X<filename, DOS issues>
Whoops! You just put a tab and a formfeed into that filename!
Remember that within double quoted strings ("like\this"), the
are more portable, too.
=head2 Why doesn't glob("*.*") get all the files?
+X<glob>
Because even on non-Unix ports, Perl's glob function follows standard
Unix globbing semantics. You'll need C<glob("*")> to get all (non-hidden)
the permissions of the file govern whether you're allowed to.
=head2 How do I select a random line from a file?
+X<file, selecting a random line>
Here's an algorithm from the Camel Book:
a number/whole/integer/float", to be precise).
=head2 How can I hope to use regular expressions without creating illegible and unmaintainable code?
+X<regex, legibility> X<regexp, legibility>
+X<regular expression, legibility> X</x>
Three techniques can make regular expressions maintainable and
understandable.
=back
=head2 I'm having trouble matching over more than one line. What's wrong?
+X<regex, multiline> X<regexp, multiline> X<regular expression, multiline>
Either you don't have more than one line in the string you're looking
at (probably), or else you aren't using the correct modifier(s) on
}
=head2 How can I pull out lines between two patterns that are themselves on different lines?
+X<..>
You can use Perl's somewhat exotic C<..> operator (documented in
L<perlop>):
}
=head2 I put a regular expression into $/ but it didn't work. What's wrong?
+X<$/, regexes in> X<$INPUT_RECORD_SEPARATOR, regexes in>
+X<$RS, regexes in>
Up to Perl 5.8.0, $/ has to be a string. This may change in 5.10,
but don't get your hopes up. Until then, you can use these examples
=head2 How do I substitute case insensitively on the LHS while preserving case on the RHS?
+X<replace, case preserving> X<substitute, case preserving>
+X<substitution, case preserving> X<s, case preserving>
Here's a lovely Perlish solution by Larry Rosler. It exploits
properties of bitwise xor on ASCII strings.
}
=head2 How can I make C<\w> match national character sets?
+X<\w>
Put C<use locale;> in your script. The \w character class is taken
from the current locale.
See L<perllocale> for details.
=head2 How can I match a locale-smart version of C</[a-zA-Z]/>?
+X<alpha>
You can use the POSIX character class syntax C</[[:alpha:]]/>
documented in L<perlre>.
the digits and the underscore, or C</[\W\d_]/>.
=head2 How can I quote a variable to use in a regex?
+X<regex, escaping> X<regexp, escaping> X<regular expression, escaping>
The Perl parser will expand $variable and @variable references in
regular expressions unless the delimiter is a single quote. Remember,
regular character, so that C<P.> matches a C<P> followed by a dot.
=head2 What is C</o> really for?
+X</o>
Using a variable in a regular expression match forces a re-evaluation
(and perhaps recompilation) each time the regular expression is
s#/\*[^*]*\*+([^/*][^*]*\*+)*/|//[^\n]*|("(\\.|[^"\\])*"|'(\\.|[^'\\])*'|.[^/"'\\]*)#defined $2 ? $2 : ""#gse;
=head2 Can I use Perl regular expressions to match balanced text?
+X<regex, matching balanced test> X<regexp, matching balanced test>
+X<regular expression, matching balanced test>
Historically, Perl regular expressions were not capable of matching
balanced text. As of more recent versions of perl including 5.6.1
but they are undocumented.
=head2 What does it mean that regexes are greedy? How can I get around it?
+X<greedy> X<greediness>
Most people mean that greedy regexes match as much as they can.
Technically speaking, it's actually the quantifiers (C<?>, C<*>, C<+>,
playing hot potato.
=head2 How do I process each word on each line?
+X<word>
Use the split function:
sort a hash (optionally by value instead of key)?".
=head2 How can I do approximate matching?
+X<match, approximate> X<matching, approximate>
See the module String::Approx available from CPAN.
=head2 How do I efficiently match many regular expressions at once?
+X<regex, efficiency> X<regexp, efficiency>
+X<regular expression, efficiency>
( contributed by brian d foy )
expressions, you can tune them for individual situations.
=head2 Why don't word-boundary searches with C<\b> work for me?
+X<\b>
(contributed by brian d foy)
=head2 Why does using $&, $`, or $' slow my program down?
+X<$MATCH> X<$&> X<$POSTMATCH> X<$'> X<$PREMATCH> X<$`>
(contributed by Anno Siegel)
string copying.
=head2 What good is C<\G> in a regular expression?
+X<\G>
You use the C<\G> anchor to start the next match on the same
string where the last match left off. The regular
pattern.
=head2 Are Perl regexes DFAs or NFAs? Are they POSIX compliant?
+X<DFA> X<NFA> X<POSIX>
While it's true that Perl's regular expressions resemble the DFAs
(deterministic finite automata) of the egrep(1) program, they are in
L<perlfaq2>).
=head2 What's wrong with using grep in a void context?
+X<grep>
The problem is that grep builds a return list, regardless of the context.
This means you're making Perl go to the trouble of building a list that
context, no lists are constructed.
=head2 How can I match strings with multibyte characters?
+X<regex, and multibyte characters> X<regexp, and multibyte characters>
+X<regular expression, and multibyte characters>
Starting from Perl 5.6 Perl has had some level of multibyte character
support. Perl 5.8 or later is recommended. Supported multibyte
=head1 NAME
+X<format> X<report> X<chart>
perlform - Perl formats
to execute; see their entries in L<perlfunc>. Fortunately, the layout is
much more legible, more like BASIC's PRINT USING statement. Think of it
as a poor man's nroff(1).
+X<nroff>
Formats, like packages and subroutines, are declared rather than
executed, so they may occur at any point in your program. (Usually it's
Field definitions are made up from a set of characters, for starting and
extending a field to its desired width. This is the complete set of
characters for field definitions:
+X<format, picture line>
+X<@> X<^> X<< < >> X<< | >> X<< > >> X<#> X<0> X<.> X<...>
+X<@*> X<^*> X<~> X<~~>
@ start of regular field
^ start of special field
=head2 Text Fields
+X<format, text field>
The length of the field is supplied by padding out the field with multiple
"E<lt>", "E<gt>", or "|" characters to specify a non-numeric field with,
=head2 Numeric Fields
+X<#> X<format, numeric field>
Using "#" as a padding character specifies a numeric field, with
right justification. An optional "." defines the position of the
=head2 The Field @* for Variable Width Multi-Line Text
+X<@*>
The field "@*" can be used for printing multi-line, nontruncated
values; it should (but need not) appear by itself on a line. A final
=head2 The Field ^* for Variable Width One-line-at-a-time Text
+X<^*>
Like "@*", this is a variable width field. The value supplied must be a
scalar variable. Perl puts the first line (up to the first "\n") of the
=head2 Specifying Values
+X<format, specifying values>
The values are specified on the following format line in the same order as
the picture fields. The expressions providing the values must be
=head2 Using Fill Mode
+X<format, fill mode>
On text fields the caret enables a kind of fill mode. Instead of an
arbitrary expression, the value supplied must be a scalar variable
=head2 Suppressing Lines Where All Fields Are Void
+X<format, suppressing lines>
Using caret fields can produce lines where all fields are blank. You can
suppress such lines by putting a "~" (tilde) character anywhere in the
=head2 Repeating Format Lines
+X<format, repeating lines>
If you put two contiguous tilde characters "~~" anywhere into a line,
the line will be repeated until all the fields on the line are exhausted,
=head2 Top of Form Processing
+X<format, top of form> X<top> X<header>
Top-of-form processing is by default handled by a format with the
same name as the current filehandle with "_TOP" concatenated to it.
yourself.
=head2 Format Variables
+X<format variables>
+X<format, variables>
The current format name is stored in the variable C<$~> (C<$FORMAT_NAME>),
and the current top of form format name is in C<$^> (C<$FORMAT_TOP_NAME>).
}
=head2 Footers
+X<format, footer> X<footer>
While $FORMAT_TOP_NAME contains the name of the current header format,
there is no corresponding mechanism to automatically do the same thing
however you like. Not very convenient, but doable.
=head2 Accessing Formatting Internals
+X<format, internals>
For low-level access to the formatting mechanism. you may use formline()
and access C<$^A> (the $ACCUMULATOR variable) directly.
=head1 NAME
+X<function>
perlfunc - Perl builtin functions
last value in the list. Some operators return a count of successful
operations. In general, they do what you want, unless you want
consistency.
+X<context>
A named array in scalar context is quite different from what would at
first glance appear to be a list in scalar context. You can't get a list
variable on failure. Other functions do not, except accidentally.
=head2 Perl Functions by Category
+X<function>
Here are Perl's functions (including things that look like
functions, like some keywords and named operators)
=over 4
=item Functions for SCALARs or strings
+X<scalar> X<string> X<character>
C<chomp>, C<chop>, C<chr>, C<crypt>, C<hex>, C<index>, C<lc>, C<lcfirst>,
C<length>, C<oct>, C<ord>, C<pack>, C<q/STRING/>, C<qq/STRING/>, C<reverse>,
C<rindex>, C<sprintf>, C<substr>, C<tr///>, C<uc>, C<ucfirst>, C<y///>
=item Regular expressions and pattern matching
+X<regular expression> X<regex> X<regexp>
C<m//>, C<pos>, C<quotemeta>, C<s///>, C<split>, C<study>, C<qr//>
=item Numeric functions
+X<numeric> X<number> X<trigonometric> X<trigonometry>
C<abs>, C<atan2>, C<cos>, C<exp>, C<hex>, C<int>, C<log>, C<oct>, C<rand>,
C<sin>, C<sqrt>, C<srand>
=item Functions for real @ARRAYs
+X<array>
C<pop>, C<push>, C<shift>, C<splice>, C<unshift>
=item Functions for list data
+X<list>
C<grep>, C<join>, C<map>, C<qw/STRING/>, C<reverse>, C<sort>, C<unpack>
=item Functions for real %HASHes
+X<hash>
C<delete>, C<each>, C<exists>, C<keys>, C<values>
=item Input and output functions
+X<I/O> X<input> X<output> X<dbm>
C<binmode>, C<close>, C<closedir>, C<dbmclose>, C<dbmopen>, C<die>, C<eof>,
C<fileno>, C<flock>, C<format>, C<getc>, C<print>, C<printf>, C<read>,
C<pack>, C<read>, C<syscall>, C<sysread>, C<syswrite>, C<unpack>, C<vec>
=item Functions for filehandles, files, or directories
+X<file> X<filehandle> X<directory> X<pipe> X<link> X<symlink>
C<-I<X>>, C<chdir>, C<chmod>, C<chown>, C<chroot>, C<fcntl>, C<glob>,
C<ioctl>, C<link>, C<lstat>, C<mkdir>, C<open>, C<opendir>,
C<umask>, C<unlink>, C<utime>
=item Keywords related to the control flow of your Perl program
+X<control flow>
C<caller>, C<continue>, C<die>, C<do>, C<dump>, C<eval>, C<exit>,
C<goto>, C<last>, C<next>, C<redo>, C<return>, C<sub>, C<wantarray>
C<scalar>, C<undef>, C<wantarray>
=item Functions for processes and process groups
+X<process> X<pid> X<process id>
C<alarm>, C<exec>, C<fork>, C<getpgrp>, C<getppid>, C<getpriority>, C<kill>,
C<pipe>, C<qx/STRING/>, C<setpgrp>, C<setpriority>, C<sleep>, C<system>,
C<times>, C<wait>, C<waitpid>
=item Keywords related to perl modules
+X<module>
C<do>, C<import>, C<no>, C<package>, C<require>, C<use>
=item Keywords related to classes and object-orientedness
+X<object> X<class> X<package>
C<bless>, C<dbmclose>, C<dbmopen>, C<package>, C<ref>, C<tie>, C<tied>,
C<untie>, C<use>
=item Low-level socket functions
+X<socket> X<sock>
C<accept>, C<bind>, C<connect>, C<getpeername>, C<getsockname>,
C<getsockopt>, C<listen>, C<recv>, C<send>, C<setsockopt>, C<shutdown>,
C<socket>, C<socketpair>
=item System V interprocess communication functions
+X<IPC> X<System V> X<semaphore> X<shared memory> X<memory> X<message>
C<msgctl>, C<msgget>, C<msgrcv>, C<msgsnd>, C<semctl>, C<semget>, C<semop>,
C<shmctl>, C<shmget>, C<shmread>, C<shmwrite>
=item Fetching user and group info
+X<user> X<group> X<password> X<uid> X<gid> X<passwd> X</etc/passwd>
C<endgrent>, C<endhostent>, C<endnetent>, C<endpwent>, C<getgrent>,
C<getgrgid>, C<getgrnam>, C<getlogin>, C<getpwent>, C<getpwnam>,
C<getpwuid>, C<setgrent>, C<setpwent>
=item Fetching network info
+X<network> X<protocol> X<host> X<hostname> X<IP> X<address> X<service>
C<endprotoent>, C<endservent>, C<gethostbyaddr>, C<gethostbyname>,
C<gethostent>, C<getnetbyaddr>, C<getnetbyname>, C<getnetent>,
C<setnetent>, C<setprotoent>, C<setservent>
=item Time-related functions
+X<time> X<date>
C<gmtime>, C<localtime>, C<time>, C<times>
=item Functions new in perl5
+X<perl5>
C<abs>, C<bless>, C<chomp>, C<chr>, C<exists>, C<formline>, C<glob>,
C<import>, C<lc>, C<lcfirst>, C<map>, C<my>, C<no>, C<our>, C<prototype>,
=back
=head2 Portability
+X<portability> X<Unix> X<portable>
Perl was born in Unix and can therefore access all common Unix
system calls. In non-Unix environments, the functionality of some
=over 8
=item -X FILEHANDLE
+X<-r>X<-w>X<-x>X<-o>X<-R>X<-W>X<-X>X<-O>X<-e>X<-z>X<-s>X<-f>X<-d>X<-l>X<-p>
+X<-S>X<-b>X<-c>X<-t>X<-u>X<-g>X<-k>X<-T>X<-B>X<-M>X<-A>X<-C>
=item -X EXPR
names, precedence is the same as any other named unary operator, and
the argument may be parenthesized like any other unary operator. The
operator may be any of:
-X<-r>X<-w>X<-x>X<-o>X<-R>X<-W>X<-X>X<-O>X<-e>X<-z>X<-s>X<-f>X<-d>X<-l>X<-p>
-X<-S>X<-b>X<-c>X<-t>X<-u>X<-g>X<-k>X<-T>X<-B>X<-M>X<-A>X<-C>
-r File is readable by effective uid/gid.
-w File is writable by effective uid/gid.
operator, no special magic will happen.)
=item abs VALUE
+X<abs> X<absolute>
=item abs
If VALUE is omitted, uses C<$_>.
=item accept NEWSOCKET,GENERICSOCKET
+X<accept>
Accepts an incoming socket connect, just as the accept(2) system call
does. Returns the packed address if it succeeded, false otherwise.
value of $^F. See L<perlvar/$^F>.
=item alarm SECONDS
+X<alarm>
+X<SIGALRM>
+X<timer>
=item alarm
For more information see L<perlipc>.
=item atan2 Y,X
+X<atan2> X<arctangent> X<tan> X<tangent>
Returns the arctangent of Y/X in the range -PI to PI.
Note that atan2(0, 0) is not well-defined.
=item bind SOCKET,NAME
+X<bind>
Binds a network address to a socket, just as the bind system call
does. Returns true if it succeeded, false otherwise. NAME should be a
L<perlipc/"Sockets: Client/Server Communication">.
=item binmode FILEHANDLE, LAYER
+X<binmode> X<binary> X<text> X<DOS> X<Windows>
=item binmode FILEHANDLE
line-termination sequences.
=item bless REF,CLASSNAME
+X<bless>
=item bless REF
See L<perlmod/"Perl Modules">.
=item caller EXPR
+X<caller> X<call stack> X<stack> X<stack trace>
=item caller
previous time C<caller> was called.
=item chdir EXPR
+X<chdir>
+X<cd>
=item chdir FILEHANDLE
passing handles produces a fatal error at run time.
=item chmod LIST
+X<chmod> X<permission> X<mode>
Changes the permissions of a list of files. The first element of the
list must be the numerical mode, which should probably be an octal
# This is identical to the chmod 0755 of the above example.
=item chomp VARIABLE
+X<chomp> X<INPUT_RECORD_SEPARATOR> X<$/> X<newline> X<eol>
=item chomp( LIST )
as C<chomp($a, $b)>.
=item chop VARIABLE
+X<chop>
=item chop( LIST )
See also L</chomp>.
=item chown LIST
+X<chown> X<owner> X<user> X<group>
Changes the owner (and group) of a list of files. The first two
elements of the list must be the I<numeric> uid and gid, in that
$can_chown_giveaway = not sysconf(_PC_CHOWN_RESTRICTED);
=item chr NUMBER
+X<chr> X<character> X<ASCII> X<Unicode>
=item chr
See L<perlunicode> and L<encoding> for more about Unicode.
=item chroot FILENAME
+X<chroot> X<root>
=item chroot
omitted, does a C<chroot> to C<$_>.
=item close FILEHANDLE
+X<close>
=item close
filehandle, usually the real filehandle name.
=item closedir DIRHANDLE
+X<closedir>
Closes a directory opened by C<opendir> and returns the success of that
system call.
=item connect SOCKET,NAME
+X<connect>
Attempts to connect to a remote socket, just as the connect system call
does. Returns true if it succeeded, false otherwise. NAME should be a
L<perlipc/"Sockets: Client/Server Communication">.
=item continue BLOCK
+X<continue>
C<continue> is actually a flow control statement rather than a function. If
there is a C<continue> BLOCK attached to a BLOCK (typically in a C<while> or
to check the condition at the top of the loop.
=item cos EXPR
+X<cos> X<cosine> X<acos> X<arccosine>
=item cos
sub acos { atan2( sqrt(1 - $_[0] * $_[0]), $_[0] ) }
=item crypt PLAINTEXT,SALT
+X<crypt> X<digest> X<hash> X<salt> X<plaintext> X<password>
+X<decrypt> X<cryptography> X<passwd>
Creates a digest string exactly like the crypt(3) function in the C
library (assuming that you actually have a version there that has not
C<Wide character in crypt>.
=item dbmclose HASH
+X<dbmclose>
[This function has been largely superseded by the C<untie> function.]
Breaks the binding between a DBM file and a hash.
=item dbmopen HASH,DBNAME,MASK
+X<dbmopen> X<dbm> X<ndbm> X<sdbm> X<gdbm>
[This function has been largely superseded by the C<tie> function.]
or die "Can't open netscape history file: $!";
=item defined EXPR
+X<defined> X<undef> X<undefined>
=item defined
See also L</undef>, L</exists>, L</ref>.
=item delete EXPR
+X<delete>
Given an expression that specifies a hash element, array element, hash slice,
or array slice, deletes the specified element(s) from the hash or array.
delete @{$ref->[$x][$y]}[$index1, $index2, @moreindices];
=item die LIST
+X<die> X<throw> X<exception> X<raise> X<$@> X<abort>
Outside an C<eval>, prints the value of LIST to C<STDERR> and
exits with the current value of C<$!> (errno). If C<$!> is C<0>,
behavior may be fixed in a future release.
=item do BLOCK
+X<do> X<block>
Not really a function. Returns the value of the last command in the
sequence of commands indicated by BLOCK. When modified by the C<while> or
See L<perlsyn> for alternative strategies.
=item do SUBROUTINE(LIST)
+X<do>
This form of subroutine call is deprecated. See L<perlsub>.
=item do EXPR
+X<do>
Uses the value of EXPR as a filename and executes the contents of the
file as a Perl script.
}
=item dump LABEL
+X<dump> X<core> X<undump>
=item dump
make your program I<appear> to run faster.
=item each HASH
+X<each> X<hash, iterator>
When called in list context, returns a 2-element list consisting of the
key and value for the next element of a hash, so that you can iterate over
See also C<keys>, C<values> and C<sort>.
=item eof FILEHANDLE
+X<eof>
+X<end of file>
+X<end-of-file>
=item eof ()
there was an error.
=item eval EXPR
+X<eval> X<try> X<catch> X<evaluate> X<parse> X<execute>
=item eval BLOCK
need to worry about this unless you are writing a Perl debugger.
=item exec LIST
+X<exec> X<execute>
=item exec PROGRAM LIST
any C<DESTROY> methods in your objects.
=item exists EXPR
+X<exists> X<autovivification>
Given an expression that specifies a hash element or array element,
returns true if the specified element in the hash or array has ever
exists &sub(); # Error
=item exit EXPR
+X<exit> X<terminate> X<abort>
=item exit
See L<perlmod> for details.
=item exp EXPR
+X<exp> X<exponential> X<antilog> X<antilogarithm> X<e>
=item exp
If EXPR is omitted, gives C<exp($_)>.
=item fcntl FILEHANDLE,FUNCTION,SCALAR
+X<fcntl>
Implements the fcntl(2) function. You'll probably have to say
or die "Can't set flags for the socket: $!\n";
=item fileno FILEHANDLE
+X<fileno>
Returns the file descriptor for a filehandle, or undefined if the
filehandle is not open. This is mainly useful for constructing
=item flock FILEHANDLE,OPERATION
+X<flock> X<lock> X<locking>
Calls flock(2), or an emulation of it, on FILEHANDLE. Returns true
for success, false on failure. Produces a fatal error if used on a
See also L<DB_File> for other flock() examples.
=item fork
+X<fork> X<child> X<parent>
Does a fork(2) system call to create a new process running the
same program at the same point. It returns the child pid to the
You should reopen those to F</dev/null> if it's any issue.
=item format
+X<format>
Declare a picture format for use by the C<write> function. For
example:
See L<perlform> for many details and examples.
=item formline PICTURE,LIST
+X<formline>
This is an internal function used by C<format>s, though you may call it,
too. It formats (see L<perlform>) a list of values according to the
C<formline> always returns true. See L<perlform> for other examples.
=item getc FILEHANDLE
+X<getc> X<getchar>
=item getc
L<perlmodlib/CPAN>.
=item getlogin
+X<getlogin> X<login>
This implements the C library function of the same name, which on most
systems returns the current login from F</etc/utmp>, if any. If null,
secure as C<getpwuid>.
=item getpeername SOCKET
+X<getpeername> X<peer>
Returns the packed sockaddr address of other end of the SOCKET connection.
$herstraddr = inet_ntoa($iaddr);
=item getpgrp PID
+X<getpgrp> X<group>
Returns the current process group for the specified PID. Use
a PID of C<0> to get the current process group for the
does not accept a PID argument, so only C<PID==0> is truly portable.
=item getppid
+X<getppid> X<parent> X<pid>
Returns the process id of the parent process.
C<Linux::Pid>.
=item getpriority WHICH,WHO
+X<getpriority> X<priority> X<nice>
Returns the current priority for a process, a process group, or a user.
(See L<getpriority(2)>.) Will raise a fatal exception if used on a
machine that doesn't implement getpriority(2).
=item getpwnam NAME
+X<getpwnam> X<getgrnam> X<gethostbyname> X<getnetbyname> X<getprotobyname>
+X<getpwuid> X<getgrgid> X<getservbyname> X<gethostbyaddr> X<getnetbyaddr>
+X<getprotobynumber> X<getservbyport> X<getpwent> X<getgrent> X<gethostent>
+X<getnetent> X<getprotoent> X<getservent> X<setpwent> X<setgrent> X<sethostent>
+X<setnetent> X<setprotoent> X<setservent> X<endpwent> X<endgrent> X<endhostent>
+X<endnetent> X<endprotoent> X<endservent>
=item getgrnam NAME
a C<User::pwent> object.
=item getsockname SOCKET
+X<getsockname>
Returns the packed sockaddr address of this end of the SOCKET connection,
in case you don't know the address because you have several different
inet_ntoa($myaddr);
=item getsockopt SOCKET,LEVEL,OPTNAME
+X<getsockopt>
Queries the option named OPTNAME associated with SOCKET at a given LEVEL.
Options may exist at multiple protocol levels depending on the socket
=item glob EXPR
+X<glob> X<wildcard> X<filename, expansion> X<expand>
=item glob
C<File::Glob> extension. See L<File::Glob> for details.
=item gmtime EXPR
+X<gmtime> X<UTC> X<Greenwich>
=item gmtime
See L<perlport/gmtime> for portability concerns.
=item goto LABEL
+X<goto> X<jump> X<jmp>
=item goto EXPR
reference.
=item grep BLOCK LIST
+X<grep>
=item grep EXPR,LIST
See also L</map> for a list composed of the results of the BLOCK or EXPR.
=item hex EXPR
+X<hex> X<hexadecimal>
=item hex
L</sprintf>, or L</unpack>.
=item import LIST
+X<import>
There is no builtin C<import> function. It is just an ordinary
method (subroutine) defined (or inherited) by modules that wish to export
for the package used. See also L</use>, L<perlmod>, and L<Exporter>.
=item index STR,SUBSTR,POSITION
+X<index> X<indexOf> X<InStr>
=item index STR,SUBSTR
is not found, C<index> returns one less than the base, ordinarily C<-1>.
=item int EXPR
+X<int> X<integer> X<truncate> X<trunc>
=item int
functions will serve you better than will int().
=item ioctl FILEHANDLE,FUNCTION,SCALAR
+X<ioctl>
Implements the ioctl(2) function. You'll probably first have to say
about improper numeric conversions.
=item join EXPR,LIST
+X<join>
Joins the separate strings of LIST into a single string with fields
separated by the value of EXPR, and returns that new string. Example:
first argument. Compare L</split>.
=item keys HASH
+X<keys> X<key>
Returns a list consisting of all the keys of the named hash.
(In scalar context, returns the number of keys.)
See also C<each>, C<values> and C<sort>.
=item kill SIGNAL, LIST
+X<kill> X<signal>
Sends a signal to a list of processes. Returns the number of
processes successfully signaled (which is not necessarily the
See L<perlipc/"Signals"> for more details.
=item last LABEL
+X<last> X<break>
=item last
C<redo> work.
=item lc EXPR
+X<lc> X<lowercase>
=item lc
If EXPR is omitted, uses C<$_>.
=item lcfirst EXPR
+X<lcfirst> X<lowercase>
=item lcfirst
If EXPR is omitted, uses C<$_>.
=item length EXPR
+X<length> X<size>
=item length
in bytes, use C<do { use bytes; length(EXPR) }>, see L<bytes>.
=item link OLDFILE,NEWFILE
+X<link>
Creates a new filename linked to the old filename. Returns true for
success, false otherwise.
=item listen SOCKET,QUEUESIZE
+X<listen>
Does the same thing that the listen system call does. Returns true if
it succeeded, false otherwise. See the example in
L<perlipc/"Sockets: Client/Server Communication">.
=item local EXPR
+X<local>
You really probably want to be using C<my> instead, because C<local> isn't
what most people think of as "local". See
for details, including issues with tied arrays and hashes.
=item localtime EXPR
+X<localtime>
=item localtime
See L<perlport/localtime> for portability concerns.
=item lock THING
+X<lock>
This function places an advisory lock on a shared variable, or referenced
object contained in I<THING> until the lock goes out of scope.
keyword.) See L<threads>.
=item log EXPR
+X<log> X<logarithm> X<e> X<ln> X<base>
=item log
See also L</exp> for the inverse operation.
=item lstat EXPR
+X<lstat>
=item lstat
The match operator. See L<perlop>.
=item map BLOCK LIST
+X<map>
=item map EXPR,LIST
and you get list of anonymous hashes each with only 1 entry.
=item mkdir FILENAME,MASK
+X<mkdir> X<md> X<directory, create>
=item mkdir FILENAME
everyone happy.
=item msgctl ID,CMD,ARG
+X<msgctl>
Calls the System V IPC function msgctl(2). You'll probably have to say
L<perlipc/"SysV IPC">, C<IPC::SysV>, and C<IPC::Semaphore> documentation.
=item msgget KEY,FLAGS
+X<msgget>
Calls the System V IPC function msgget(2). Returns the message queue
id, or the undefined value if there is an error. See also
L<perlipc/"SysV IPC"> and C<IPC::SysV> and C<IPC::Msg> documentation.
=item msgrcv ID,VAR,SIZE,TYPE,FLAGS
+X<msgrcv>
Calls the System V IPC function msgrcv to receive a message from
message queue ID into variable VAR with a maximum message size of
C<IPC::SysV::Msg> documentation.
=item msgsnd ID,MSG,FLAGS
+X<msgsnd>
Calls the System V IPC function msgsnd to send the message MSG to the
message queue ID. MSG must begin with the native long integer message
and C<IPC::SysV::Msg> documentation.
=item my EXPR
+X<my>
=item my TYPE EXPR
L<attributes>, and L<Attribute::Handlers>.
=item next LABEL
+X<next> X<continue>
=item next
C<redo> work.
=item no Module VERSION LIST
+X<no>
=item no Module VERSION
See the C<use> function, of which C<no> is the opposite.
=item oct EXPR
+X<oct> X<octal> X<hex> X<hexadecimal> X<binary> X<bin>
=item oct
conversion assumes base 10.)
=item open FILEHANDLE,EXPR
+X<open> X<pipe> X<file, open> X<fopen>
=item open FILEHANDLE,MODE,EXPR
See L</seek> for some details about mixing reading and writing.
=item opendir DIRHANDLE,EXPR
+X<opendir>
Opens a directory named EXPR for processing by C<readdir>, C<telldir>,
C<seekdir>, C<rewinddir>, and C<closedir>. Returns true if successful.
DIRHANDLEs have their own namespace separate from FILEHANDLEs.
=item ord EXPR
+X<ord> X<encoding>
=item ord
See L<perlunicode> and L<encoding> for more about Unicode.
=item our EXPR
+X<our> X<global>
=item our EXPR TYPE
subject to change.
=item pack TEMPLATE,LIST
+X<pack>
Takes a LIST of values and converts it into a string using the rules
given by the TEMPLATE. The resulting string is the concatenation of
The same template may generally also be used in unpack().
=item package NAMESPACE
+X<package> X<module> X<namespace>
=item package
and classes. See L<perlsub> for other scoping issues.
=item pipe READHANDLE,WRITEHANDLE
+X<pipe>
Opens a pair of connected pipes like the corresponding system call.
Note that if you set up a loop of piped processes, deadlock can occur
See L<perlvar/$^F>.
=item pop ARRAY
+X<pop> X<stack>
=item pop
array in subroutines, just like C<shift>.
=item pos SCALAR
+X<pos> X<match, position>
=item pos
L<perlop>.
=item print FILEHANDLE LIST
+X<print>
=item print LIST
print { $OK ? STDOUT : STDERR } "stuff\n";
=item printf FILEHANDLE FORMAT, LIST
+X<printf>
=item printf FORMAT, LIST
error prone.
=item prototype FUNCTION
+X<prototype>
Returns the prototype of a function as a string (or C<undef> if the
function has no prototype). FUNCTION is a reference to, or the name of,
prototype is returned.
=item push ARRAY,LIST
+X<push>, X<stack>
Treats ARRAY as a stack, and pushes the values of LIST
onto the end of ARRAY. The length of ARRAY increases by the length of
Generalized quotes. See L<perlop/"Regexp Quote-Like Operators">.
=item quotemeta EXPR
+X<quotemeta> X<metacharacter>
=item quotemeta
If EXPR is omitted, uses C<$_>.
=item rand EXPR
+X<rand> X<random>
=item rand
with the wrong number of RANDBITS.)
=item read FILEHANDLE,SCALAR,LENGTH,OFFSET
+X<read>
=item read FILEHANDLE,SCALAR,LENGTH
in that case pretty much any characters can be read.
=item readdir DIRHANDLE
+X<readdir>
Returns the next directory entry for a directory opened by C<opendir>.
If used in list context, returns all the rest of the entries in the
closedir DIR;
=item readline EXPR
+X<readline> X<gets> X<fgets>
Reads from the filehandle whose typeglob is contained in EXPR. In scalar
context, each call reads and returns the next line, until end-of-file is
}
=item readlink EXPR
+X<readlink>
=item readlink
omitted, uses C<$_>.
=item readpipe EXPR
+X<readpipe>
EXPR is executed as a system command.
The collected standard output of the command is returned.
operator is discussed in more detail in L<perlop/"I/O Operators">.
=item recv SOCKET,SCALAR,LENGTH,FLAGS
+X<recv>
Receives a message on a socket. Attempts to receive LENGTH characters
of data into variable SCALAR from the specified SOCKET filehandle.
in that case pretty much any characters can be read.
=item redo LABEL
+X<redo>
=item redo
C<redo> work.
=item ref EXPR
+X<ref> X<reference>
=item ref
See also L<perlref>.
=item rename OLDNAME,NEWNAME
+X<rename> X<move> X<mv> X<ren>
Changes the name of a file; an existing file NEWNAME will be
clobbered. Returns true for success, false otherwise.
rename(2) manpage or equivalent system documentation for details.
=item require VERSION
+X<require>
=item require EXPR
For a yet-more-powerful import facility, see L</use> and L<perlmod>.
=item reset EXPR
+X<reset>
=item reset
See L</my>.
=item return EXPR
+X<return>
=item return
evaluated.)
=item reverse LIST
+X<reverse> X<rev> X<invert>
In list context, returns a list value consisting of the elements
of LIST in the opposite order. In scalar context, concatenates the
%by_name = reverse %by_address; # Invert the hash
=item rewinddir DIRHANDLE
+X<rewinddir>
Sets the current position to the beginning of the directory for the
C<readdir> routine on DIRHANDLE.
=item rindex STR,SUBSTR,POSITION
+X<rindex>
=item rindex STR,SUBSTR
last occurrence at or before that position.
=item rmdir FILENAME
+X<rmdir> X<rd> X<directory, remove>
=item rmdir
The substitution operator. See L<perlop>.
=item scalar EXPR
+X<scalar> X<context>
Forces EXPR to be interpreted in scalar context and returns the value
of EXPR.
See L<perlop> for more details on unary operators and the comma operator.
=item seek FILEHANDLE,POSITION,WHENCE
+X<seek> X<fseek> X<filehandle, position>
Sets FILEHANDLE's position, just like the C<fseek> call of C<stdio>.
FILEHANDLE may be an expression whose value gives the name of the
}
=item seekdir DIRHANDLE,POS
+X<seekdir>
Sets the current position for the C<readdir> routine on DIRHANDLE. POS
must be a value returned by C<telldir>. C<seekdir> also has the same caveats
routine.
=item select FILEHANDLE
+X<select> X<filehandle, default>
=item select
STDERR->autoflush(1);
=item select RBITS,WBITS,EBITS,TIMEOUT
+X<select>
This calls the select(2) system call with the bit masks specified, which
can be constructed using C<fileno> and C<vec>, along these lines:
then only on POSIX systems. You have to use C<sysread> instead.
=item semctl ID,SEMNUM,CMD,ARG
+X<semctl>
Calls the System V IPC function C<semctl>. You'll probably have to say
documentation.
=item semget KEY,NSEMS,FLAGS
+X<semget>
Calls the System V IPC function semget. Returns the semaphore id, or
the undefined value if there is an error. See also
documentation.
=item semop KEY,OPSTRING
+X<semop>
Calls the System V IPC function semop to perform semaphore operations
such as signalling and waiting. OPSTRING must be a packed array of
documentation.
=item send SOCKET,MSG,FLAGS,TO
+X<send>
=item send SOCKET,MSG,FLAGS
in that case pretty much any characters can be sent.
=item setpgrp PID,PGRP
+X<setpgrp> X<group>
Sets the current process group for the specified PID, C<0> for the current
process. Will produce a fatal error if used on a machine that doesn't
C<POSIX::setsid()>.
=item setpriority WHICH,WHO,PRIORITY
+X<setpriority> X<priority> X<nice> X<renice>
Sets the current priority for a process, a process group, or a user.
(See setpriority(2).) Will produce a fatal error if used on a machine
that doesn't implement setpriority(2).
=item setsockopt SOCKET,LEVEL,OPTNAME,OPTVAL
+X<setsockopt>
Sets the socket option requested. Returns undefined if there is an
error. OPTVAL may be specified as C<undef> if you don't want to pass an
argument.
=item shift ARRAY
+X<shift>
=item shift
right end.
=item shmctl ID,CMD,ARG
+X<shmctl>
Calls the System V IPC function shmctl. You'll probably have to say
See also L<perlipc/"SysV IPC"> and C<IPC::SysV> documentation.
=item shmget KEY,SIZE,FLAGS
+X<shmget>
Calls the System V IPC function shmget. Returns the shared memory
segment id, or the undefined value if there is an error.
See also L<perlipc/"SysV IPC"> and C<IPC::SysV> documentation.
=item shmread ID,VAR,POS,SIZE
+X<shmread>
+X<shmwrite>
=item shmwrite ID,STRING,POS,SIZE
C<IPC::SysV> documentation, and the C<IPC::Shareable> module from CPAN.
=item shutdown SOCKET,HOW
+X<shutdown>
Shuts down a socket connection in the manner indicated by HOW, which
has the same interpretation as in the system call of the same name.
processes.
=item sin EXPR
+X<sin> X<sine> X<asin> X<arcsine>
=item sin
sub asin { atan2($_[0], sqrt(1 - $_[0] * $_[0])) }
=item sleep EXPR
+X<sleep> X<pause>
=item sleep
See also the POSIX module's C<pause> function.
=item socket SOCKET,DOMAIN,TYPE,PROTOCOL
+X<socket>
Opens a socket of the specified kind and attaches it to filehandle
SOCKET. DOMAIN, TYPE, and PROTOCOL are specified the same as for
value of $^F. See L<perlvar/$^F>.
=item socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL
+X<socketpair>
Creates an unnamed pair of sockets in the specified domain, of the
specified type. DOMAIN, TYPE, and PROTOCOL are specified the same as
sockets but not socketpair.
=item sort SUBNAME LIST
+X<sort> X<qsort> X<quicksort> X<mergesort>
=item sort BLOCK LIST
@result = sort { $a <=> $b } grep { $_ == $_ } @input;
=item splice ARRAY,OFFSET,LENGTH,LIST
+X<splice>
=item splice ARRAY,OFFSET,LENGTH
if (&aeq($len,@foo[1..$len],0+@bar,@bar)) { ... }
=item split /PATTERN/,EXPR,LIMIT
+X<split>
=item split /PATTERN/,EXPR
# @fields is (1, 'A', 2, undef, 3)
=item sprintf FORMAT, LIST
+X<sprintf>
Returns a string formatted by the usual C<printf> conventions of the C
library function C<sprintf>. See below for more details
effect as the C<-> flag: left-justification.
=item precision, or maximum width
+X<precision>
You can specify a precision (for numeric conversions) or a maximum
width (for string conversions) by specifying a C<.> followed by a number.
See L<perllocale>.
=item sqrt EXPR
+X<sqrt> X<root> X<square root>
=item sqrt
print sqrt(-2); # prints 1.4142135623731i
=item srand EXPR
+X<srand> X<seed> X<randseed>
=item srand
one-third of the time. So don't do that.
=item stat FILEHANDLE
+X<stat> X<file, status>
=item stat EXPR
instead of the target file behind the link, use the C<lstat> function.
=item study SCALAR
+X<study>
=item study
}
=item sub NAME BLOCK
+X<sub>
=item sub NAME (PROTO) BLOCK
information about attributes.
=item substr EXPR,OFFSET,LENGTH,REPLACEMENT
+X<substr> X<substring> X<mid> X<left> X<right>
=item substr EXPR,OFFSET,LENGTH
unspecified.
=item symlink OLDFILE,NEWFILE
+X<symlink> X<link> X<symbolic link> X<link, symbolic>
Creates a new filename symbolically linked to the old filename.
Returns C<1> for success, C<0> otherwise. On systems that don't support
$symlink_exists = eval { symlink("",""); 1 };
=item syscall NUMBER, LIST
+X<syscall> X<system call>
Calls the system call specified as the first element of the list,
passing the remaining elements as arguments to the system call. If
problem by using C<pipe> instead.
=item sysopen FILEHANDLE,FILENAME,MODE
+X<sysopen>
=item sysopen FILEHANDLE,FILENAME,MODE,PERMS
Some of the most common values are C<O_RDONLY> for opening the file in
read-only mode, C<O_WRONLY> for opening the file in write-only mode,
and C<O_RDWR> for opening the file in read-write mode.
+X<O_RDONLY> X<O_RDWR> X<O_WRONLY>
For historical reasons, some values work on almost every system
supported by perl: zero means read-only, one means write-only, and two
the PERMS argument to C<sysopen>, Perl uses the octal value C<0666>.
These permission values need to be in octal, and are modified by your
process's current C<umask>.
+X<O_CREAT>
In many systems the C<O_EXCL> flag is available for opening files in
exclusive mode. This is B<not> locking: exclusiveness means here that
is set as well. Setting C<O_CREAT|O_EXCL> prevents the file from
being opened if it is a symbolic link. It does not protect against
symbolic links in the file's path.
+X<O_EXCL>
Sometimes you may want to truncate an already-existing file. This
can be done using the C<O_TRUNC> flag. The behavior of
C<O_TRUNC> with C<O_RDONLY> is undefined.
+X<O_TRUNC>
You should seldom if ever use C<0644> as argument to C<sysopen>, because
that takes away the user's option to have a more permissive umask.
See L<perlopentut> for a kinder, gentler explanation of opening files.
=item sysread FILEHANDLE,SCALAR,LENGTH,OFFSET
+X<sysread>
=item sysread FILEHANDLE,SCALAR,LENGTH
See L</binmode>, L</open>, and the C<open> pragma, L<open>.
=item sysseek FILEHANDLE,POSITION,WHENCE
+X<sysseek> X<lseek>
Sets FILEHANDLE's system position in bytes using the system call
lseek(2). FILEHANDLE may be an expression whose value gives the name
the new position.
=item system LIST
+X<system> X<shell>
=item system PROGRAM LIST
See L<perlop/"`STRING`"> and L</exec> for details.
=item syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET
+X<syswrite>
=item syswrite FILEHANDLE,SCALAR,LENGTH
See L</binmode>, L</open>, and the C<open> pragma, L<open>.
=item tell FILEHANDLE
+X<tell>
=item tell
Those functions ignore the buffering, while tell() does not.
=item telldir DIRHANDLE
+X<telldir>
Returns the current position of the C<readdir> routines on DIRHANDLE.
Value may be given to C<seekdir> to access a particular location in a
compaction as the corresponding system library routine.
=item tie VARIABLE,CLASSNAME,LIST
+X<tie>
This function binds a variable to a package class that will provide the
implementation for the variable. VARIABLE is the name of the variable
For further details see L<perltie>, L<"tied VARIABLE">.
=item tied VARIABLE
+X<tied>
Returns a reference to the object underlying VARIABLE (the same value
that was originally returned by the C<tie> call that bound the variable
package.
=item time
+X<time> X<epoch>
Returns the number of non-leap seconds since whatever time the system
considers to be the epoch, suitable for feeding to C<gmtime> and
See L<perlfaq8> for details.
=item times
+X<times>
Returns a four-element list giving the user and system times, in
seconds, for this process and the children of this process.
The transliteration operator. Same as C<y///>. See L<perlop>.
=item truncate FILEHANDLE,LENGTH
+X<truncate>
=item truncate EXPR,LENGTH
file.
=item uc EXPR
+X<uc> X<uppercase> X<toupper>
=item uc
If EXPR is omitted, uses C<$_>.
=item ucfirst EXPR
+X<ucfirst> X<uppercase>
=item ucfirst
If EXPR is omitted, uses C<$_>.
=item umask EXPR
+X<umask>
=item umask
string of octal digits. See also L</oct>, if all you have is a string.
=item undef EXPR
+X<undef> X<undefine>
=item undef
Note that this is a unary operator, not a list operator.
=item unlink LIST
+X<unlink> X<delete> X<remove> X<rm>
=item unlink
If LIST is omitted, uses C<$_>.
=item unpack TEMPLATE,EXPR
+X<unpack>
=item unpack TEMPLATE
See L</pack> for more examples and notes.
=item untie VARIABLE
+X<untie>
Breaks the binding between a variable and a package. (See C<tie>.)
Has no effect if the variable is not tied.
=item unshift ARRAY,LIST
+X<unshift>
Does the opposite of a C<shift>. Or the opposite of a C<push>,
depending on how you look at it. Prepends list to the front of the
reverse.
=item use Module VERSION LIST
+X<use> X<module> X<import>
=item use Module VERSION
functionality from the command-line.
=item utime LIST
+X<utime>
Changes the access and modification times on each file of a list of
files. The first two elements of the list must be the NUMERICAL access
uninitialized warning.
=item values HASH
+X<values>
Returns a list consisting of all the values of the named hash.
(In a scalar context, returns the number of values.)
See also C<keys>, C<each>, and C<sort>.
=item vec EXPR,OFFSET,BITS
+X<vec> X<bit> X<bit vector>
Treats the string in EXPR as a bit vector made up of elements of
width BITS, and returns the value of the element specified by OFFSET
vec($_, 3, 8) = 128 == 2147483648 00000000000000000000000000000001
=item wait
+X<wait>
Behaves like the wait(2) system call on your system: it waits for a child
process to terminate and returns the pid of the deceased process, or
being automatically reaped, as described in L<perlipc>.
=item waitpid PID,FLAGS
+X<waitpid>
Waits for a particular child process to terminate and returns the pid of
the deceased process, or C<-1> if there is no such child process. On some
and for other examples.
=item wantarray
+X<wantarray> X<context>
Returns true if the context of the currently executing subroutine or
C<eval> is looking for a list value. Returns false if the context is
This function should have been named wantlist() instead.
=item warn LIST
+X<warn> X<warning> X<STDERR>
Produces a message on STDERR just like C<die>, but doesn't exit or throw
an exception.
carp() and cluck() functions.
=item write FILEHANDLE
+X<write>
=item write EXPR
=head1 NAME
+X<warning, lexical> X<warnings> X<warning>
perllexwarn - Perl Lexical Warnings
=over 5
=item B<-w>
+X<-w>
This is the existing flag. If the lexical warnings pragma is B<not>
used in any of you code, or any of the modules that you use, this flag
details of how this flag interacts with lexical warnings.
=item B<-W>
+X<-W>
If the B<-W> flag is used on the command line, it will enable all warnings
throughout the program regardless of whether warnings were disabled
Think of it as the Perl equivalent of the "lint" command.
=item B<-X>
+X<-X>
Does the exact opposite to the B<-W> flag, i.e. it disables all warnings.
code (using a C<local $^W=0>) if it really wants to, but not vice-versa.
=head2 Category Hierarchy
+X<warning, categories>
A hierarchy of "categories" have been defined to allow groups of warnings
to be enabled/disabled in isolation.
=head2 Fatal Warnings
+X<warning, fatal>
The presence of the word "FATAL" in the category list will escalate any
warnings detected from the categories specified in the lexical scope
use warnings FATAL => 'all', NONFATAL => 'syntax';
=head2 Reporting Warnings from a Module
+X<warning, reporting> X<warning, registering>
The C<warnings> pragma provides a number of functions that are useful for
module authors. These are used when you want to report a module-specific
=head1 DESCRIPTION
=head2 Packages
+X<package> X<namespace> X<variable, global> X<global variable> X<global>
Perl provides a mechanism for alternative namespaces to protect
packages from stomping on each other's variables. In fact, there's
C<"This is $owner's house">, you'll be accessing C<$owner::s>; that is,
the $s variable in package C<owner>, which is probably not what you meant.
Use braces to disambiguate, as in C<"This is ${owner}'s house">.
+X<::> X<'>
Packages may themselves contain package separators, as in
C<$OUTER::INNER::var>. This implies nothing about the order of
have a package called C<m>, C<s>, or C<y>, then you can't use the
qualified form of an identifier because it would be instead interpreted
as a pattern match, a substitution, or a transliteration.
+X<variable, punctuation>
Variables beginning with underscore used to be forced into package
main, but we decided it was more useful for package writers to be able
and L<perlref> regarding closures.
=head2 Symbol Tables
+X<symbol table> X<stash> X<%::> X<%main::> X<typeglob> X<glob> X<alias>
The symbol table for a package happens to be stored in the hash of that
name with two colons appended. The main symbol table's name is thus
explicitly.
Another use of symbol tables is for making "constant" scalars.
+X<constant> X<scalar, constant>
*PI = \3.14159265358979;
(see L<perlobj>).
=head2 BEGIN, CHECK, INIT and END
+X<BEGIN> X<CHECK> X<INIT> X<END>
Four specially named code blocks are executed at the beginning and at the end
of a running Perl program. These are the C<BEGIN>, C<CHECK>, C<INIT>, and
going to pass to C<exit()>. You can modify C<$?> to change the exit
value of the program. Beware of changing C<$?> by accident (e.g. by
running something via C<system>).
+X<$?>
C<CHECK> and C<INIT> code blocks are useful to catch the transition between
the compilation phase and the execution phase of the main program.
__END__
=head2 Perl Classes
+X<class> X<@ISA>
There is no special class syntax in Perl, but a package may act
as a class if it provides subroutines to act as methods. Such a
For more on this, see L<perltoot> and L<perlobj>.
=head2 Perl Modules
+X<module>
A module is just a set of related functions in a library file, i.e.,
a Perl package with the same name as the file. It is specifically
autoloading, the user can say just C<use POSIX> to get it all.
=head2 Making your module threadsafe
+X<threadsafe> X<thread safe>
+X<module, threadsafe> X<module, thread safe>
+X<CLONE> X<CLONE_SKIP> X<thread> X<threads> X<ithread>
Since 5.6.0, Perl has had support for a new type of threads called
interpreter threads (ithreads). These threads can be used explicitly
=head1 NAME
+X<object> X<OOP>
perlobj - Perl objects
We'll cover these points now in more depth.
=head2 An Object is Simply a Reference
+X<object> X<bless> X<constructor> X<new>
Unlike say C++, Perl doesn't provide any special syntax for
constructors. A constructor is merely a subroutine that returns a
operated on the object and not on the reference.
=head2 A Class is Simply a Package
+X<class> X<package> X<@ISA> X<inheritance>
Unlike say C++, Perl doesn't provide any special syntax for class
definitions. You use a package as a class by putting method
last base class. Several commonly used methods are automatically
supplied in the UNIVERSAL class; see L<"Default UNIVERSAL methods"> for
more details.
+X<UNIVERSAL> X<base class> X<class, base>
If a missing method is found in a base class, it is cached
in the current class for efficiency. Changing @ISA or defining new
AUTOLOAD is found, this method is called on behalf of the missing method,
setting the package global $AUTOLOAD to be the fully qualified name of
the method that was intended to be called.
+X<AUTOLOAD>
If none of that works, Perl finally gives up and complains.
If you want to stop the AUTOLOAD inheritance say simply
+X<AUTOLOAD>
sub AUTOLOAD;
The only problem with this is that you can't sure that you aren't using
a piece of the hash that isn't already used. A reasonable workaround
is to prepend your fieldname in the hash with the package name.
+X<inheritance, method> X<inheritance, data>
sub bump {
my $self = shift;
}
=head2 A Method is Simply a Subroutine
+X<method>
Unlike say C++, Perl doesn't provide any special syntax for method
definition. (It does provide a little syntax for method invocation
}
=head2 Method Invocation
+X<invocation> X<method> X<arrow> X<< -> >>
For various historical and other reasons, Perl offers two equivalent
ways to write a method call. The simpler and more common way is to use
As a special case of the above, you may use the C<SUPER> pseudo-class to
tell Perl to start looking for the method in the packages named in the
current class's C<@ISA> list.
+X<SUPER>
package MyCritter;
use base 'Critter'; # sets @MyCritter::ISA = ('Critter');
C<SUPER> pseudo-class can only currently be used as a modifier to a method
name, but not in any of the other ways that class names are normally used,
eg:
+X<SUPER>
something->SUPER::method(...); # OK
SUPER::method(...); # WRONG
my $fred = (reverse "rettirC")->find(reverse "derF");
=head2 Indirect Object Syntax
+X<indirect object syntax> X<invocation, indirect> X<indirect>
The other way to invoke a method is by using the so-called "indirect
object" notation. This syntax was available in Perl 4 long before
familiar with it.
=head2 Default UNIVERSAL methods
+X<UNIVERSAL>
The C<UNIVERSAL> package automatically contains the following methods that
are inherited by all other classes:
=over 4
=item isa(CLASS)
+X<isa>
C<isa> returns I<true> if its object is blessed into a subclass of C<CLASS>
If you need to determine whether you've received a valid invocant, use the
C<blessed> function from L<Scalar::Util>:
+X<invocant> X<blessed>
if (blessed($ref) && $ref->isa( 'Some::Class')) {
# ...
blessed into, or C<undef>.
=item can(METHOD)
+X<can>
C<can> checks to see if its object has a method called C<METHOD>,
if it does then a reference to the sub is returned, if it does not then
The same caveats for calling C<UNIVERSAL::isa> directly apply here, too.
=item VERSION( [NEED] )
+X<VERSION>
C<VERSION> returns the version number of the class (package). If the
NEED argument is given then it will check that the current version (as
available to your program (and you should not do so).
=head2 Destructors
+X<destructor> X<DESTROY>
When the last reference to an object goes away, the object is
automatically destroyed. (This may even be after you exit, if you've
with it for the next six months or so.
=head2 Two-Phased Garbage Collection
+X<garbage collection> X<GC> X<circular reference>
+X<reference, circular> X<DESTROY> X<destructor>
For most purposes, Perl uses a fast and simple, reference-based
garbage collection system. That means there's an extra
=head1 NAME
+X<operator>
perlop - Perl operators and precedence
=head1 DESCRIPTION
-=head2 Operator Precedence and Associativity
+=head2 Operator Precedence and Associativity
+X<operator, precedence> X<precedence> X<associativity>
Operator precedence and associativity work in Perl more or less like
they do in mathematics.
Many operators can be overloaded for objects. See L<overload>.
=head2 Terms and List Operators (Leftward)
+X<list operator> X<operator, list> X<term>
A TERM has the highest precedence in Perl. They include variables,
quote and quote-like operators, any expression in parentheses,
as well as L<"I/O Operators">.
=head2 The Arrow Operator
+X<arrow> X<dereference> X<< -> >>
"C<< -> >>" is an infix dereference operator, just as it is in C
and C++. If the right side is either a C<[...]>, C<{...}>, or a
or a class name (that is, a package name). See L<perlobj>.
=head2 Auto-increment and Auto-decrement
+X<increment> X<auto-increment> X<++> X<decrement> X<auto-decrement> X<-->
"++" and "--" work as in C. That is, if placed before a variable,
they increment or decrement the variable by one before returning the
The auto-decrement operator is not magical.
=head2 Exponentiation
+X<**> X<exponentiation> X<power>
Binary "**" is the exponentiation operator. It binds even more
tightly than unary minus, so -2**4 is -(2**4), not (-2)**4. (This is
internally.)
=head2 Symbolic Unary Operators
+X<unary operator> X<operator, unary>
Unary "!" performs logical negation, i.e., "not". See also C<not> for a lower
precedence version of this.
+X<!>
Unary "-" performs arithmetic negation if the operand is numeric. If
the operand is an identifier, a string consisting of a minus sign
starts with a plus or minus, a string starting with the opposite sign
is returned. One effect of these rules is that -bareword is equivalent
to the string "-bareword".
+X<-> X<negation, arithmetic>
Unary "~" performs bitwise negation, i.e., 1's complement. For
example, C<0666 & ~027> is 0640. (See also L<Integer Arithmetic> and
platform-dependent: ~0 is 32 bits wide on a 32-bit platform, but 64
bits wide on a 64-bit platform, so if you are expecting a certain bit
width, remember to use the & operator to mask off the excess bits.
+X<~> X<negation, binary>
Unary "+" has no effect whatsoever, even on strings. It is useful
syntactically for separating a function name from a parenthesized expression
that would otherwise be interpreted as the complete list of function
arguments. (See examples above under L<Terms and List Operators (Leftward)>.)
+X<+>
Unary "\" creates a reference to whatever follows it. See L<perlreftut>
and L<perlref>. Do not confuse this behavior with the behavior of
backslash within a string, although both forms do convey the notion
of protecting the next thing from interpolation.
+X<\> X<reference> X<backslash>
=head2 Binding Operators
+X<binding> X<operator, binding> X<=~> X<!~>
Binary "=~" binds a scalar expression to a pattern match. Certain operations
search or modify the string $_ by default. This operator makes that kind
the logical sense.
=head2 Multiplicative Operators
+X<operator, multiplicative>
Binary "*" multiplies two numbers.
+X<*>
Binary "/" divides two numbers.
+X</> X<slash>
Binary "%" computes the modulus of two numbers. Given integer
operands C<$a> and C<$b>: If C<$b> is positive, then C<$a % $b> is
to the modulus operator as implemented by your C compiler. This
operator is not as well defined for negative operands, but it will
execute faster.
+X<%> X<remainder> X<modulus> X<mod>
Binary "x" is the repetition operator. In scalar context or if the left
operand is not enclosed in parentheses, it returns a string consisting
parentheses or is a list formed by C<qw/STRING/>, it repeats the list.
If the right operand is zero or negative, it returns an empty string
or an empty list, depending on the context.
+X<x>
print '-' x 80; # print row of dashes
=head2 Additive Operators
+X<operator, additive>
Binary "+" returns the sum of two numbers.
+X<+>
Binary "-" returns the difference of two numbers.
+X<->
Binary "." concatenates two strings.
+X<string, concatenation> X<concatenation>
+X<cat> X<concat> X<concatenate> X<.>
=head2 Shift Operators
+X<shift operator> X<operator, shift> X<<< << >>>
+X<<< >> >>> X<right shift> X<left shift> X<bitwise shift>
+X<shl> X<shr> X<shift, right> X<shift, left>
Binary "<<" returns the value of its left argument shifted left by the
number of bits specified by the right argument. Arguments should be
of bits is also undefined.
=head2 Named Unary Operators
+X<operator, named unary>
The various named unary operators are treated as functions with one
argument, with optional parentheses.
treated like named unary operators, but they don't follow this functional
parenthesis rule. That means, for example, that C<-f($file).".bak"> is
equivalent to C<-f "$file.bak">.
+X<-X> X<filetest> X<operator, filetest>
See also L<"Terms and List Operators (Leftward)">.
=head2 Relational Operators
+X<relational operator> X<operator, relational>
Binary "<" returns true if the left argument is numerically less than
the right argument.
+X<< < >>
Binary ">" returns true if the left argument is numerically greater
than the right argument.
+X<< > >>
Binary "<=" returns true if the left argument is numerically less than
or equal to the right argument.
+X<< <= >>
Binary ">=" returns true if the left argument is numerically greater
than or equal to the right argument.
+X<< >= >>
Binary "lt" returns true if the left argument is stringwise less than
the right argument.
+X<< lt >>
Binary "gt" returns true if the left argument is stringwise greater
than the right argument.
+X<< gt >>
Binary "le" returns true if the left argument is stringwise less than
or equal to the right argument.
+X<< le >>
Binary "ge" returns true if the left argument is stringwise greater
than or equal to the right argument.
+X<< ge >>
=head2 Equality Operators
+X<equality> X<equal> X<equals> X<operator, equality>
Binary "==" returns true if the left argument is numerically equal to
the right argument.
+X<==>
Binary "!=" returns true if the left argument is numerically not equal
to the right argument.
+X<!=>
Binary "<=>" returns -1, 0, or 1 depending on whether the left
argument is numerically less than, equal to, or greater than the right
"<=" or ">=" anything (even NaN), so those 5 return false. NaN != NaN
returns true, as does NaN != anything else. If your platform doesn't
support NaNs then NaN is just a string with numeric value 0.
+X<< <=> >> X<spaceship>
perl -le '$a = "NaN"; print "No NaN support here" if $a == $a'
perl -le '$a = "NaN"; print "NaN support here" if $a != $a'
Binary "eq" returns true if the left argument is stringwise equal to
the right argument.
+X<eq>
Binary "ne" returns true if the left argument is stringwise not equal
to the right argument.
+X<ne>
Binary "cmp" returns -1, 0, or 1 depending on whether the left
argument is stringwise less than, equal to, or greater than the right
argument.
+X<cmp>
"lt", "le", "ge", "gt" and "cmp" use the collation (sort) order specified
by the current locale if C<use locale> is in effect. See L<perllocale>.
=head2 Bitwise And
+X<operator, bitwise, and> X<bitwise and> X<&>
Binary "&" returns its operands ANDed together bit by bit.
(See also L<Integer Arithmetic> and L<Bitwise String Operators>.)
print "Even\n" if ($x & 1) == 0;
=head2 Bitwise Or and Exclusive Or
+X<operator, bitwise, or> X<bitwise or> X<|> X<operator, bitwise, xor>
+X<bitwise xor> X<^>
Binary "|" returns its operands ORed together bit by bit.
(See also L<Integer Arithmetic> and L<Bitwise String Operators>.)
print "false\n" if (8 | 2) != 10;
=head2 C-style Logical And
+X<&&> X<logical and> X<operator, logical, and>
Binary "&&" performs a short-circuit logical AND operation. That is,
if the left operand is false, the right operand is not even evaluated.
is evaluated.
=head2 C-style Logical Or
+X<||> X<operator, logical, or>
Binary "||" performs a short-circuit logical OR operation. That is,
if the left operand is true, the right operand is not even evaluated.
is evaluated.
=head2 C-style Logical Defined-Or
+X<//> X<operator, logical, defined-or>
Although it has no direct equivalent in C, Perl's C<//> operator is related
to its C-style or. In fact, it's exactly the same as C<||>, except that it
Using "or" for assignment is unlikely to do what you want; see below.
=head2 Range Operators
+X<operator, range> X<range> X<..> X<...>
Binary ".." is the range operator, which is really two different
operators depending on the context. In list context, it returns a
@list = (2.18 .. 3.14); # same as @list = (2 .. 3);
=head2 Conditional Operator
+X<operator, conditional> X<operator, ternary> X<ternary> X<?:>
Ternary "?:" is the conditional operator, just as in C. It works much
like an if-then-else. If the argument before the ? is true, the
$a += ($a % 2) ? 10 : 2;
=head2 Assignment Operators
+X<assignment> X<operator, assignment> X<=> X<**=> X<+=> X<*=> X<&=>
+X<<< <<= >>> X<&&=> X<-=> X</=> X<|=> X<<< >>= >>> X<||=> X<.=>
+X<%=> X<^=> X<x=>
"=" is the ordinary assignment operator.
side of the assignment.
=head2 Comma Operator
+X<comma> X<operator, comma> X<,>
Binary "," is the comma operator. In scalar context it evaluates
its left argument, throws that value away, then evaluates its right
login( $username => $password );
=head2 List Operators (Rightward)
+X<operator, list, rightward> X<list operator>
On the right side of a list operator, it has very low precedence,
such that it controls all comma-separated expressions found there.
See also discussion of list operators in L<Terms and List Operators (Leftward)>.
=head2 Logical Not
+X<operator, logical, not> X<not>
Unary "not" returns the logical negation of the expression to its right.
It's the equivalent of "!" except for the very low precedence.
=head2 Logical And
+X<operator, logical, and> X<and>
Binary "and" returns the logical conjunction of the two surrounding
expressions. It's equivalent to && except for the very low
expression is evaluated only if the left expression is true.
=head2 Logical or, Defined or, and Exclusive Or
+X<operator, logical, or> X<operator, logical, xor> X<operator, logical, err>
+X<operator, logical, defined or> X<operator, logical, exclusive or>
+X<or> X<xor> X<err>
Binary "or" returns the logical disjunction of the two surrounding
expressions. It's equivalent to || except for the very low precedence.
It cannot short circuit, of course.
=head2 C Operators Missing From Perl
+X<operator, missing from perl> X<&> X<*>
+X<typecasting> X<(TYPE)>
Here is what C has that Perl doesn't:
=back
=head2 Quote and Quote-like Operators
+X<operator, quote> X<operator, quote-like> X<q> X<qq> X<qx> X<qw> X<m>
+X<qr> X<s> X<tr> X<'> X<''> X<"> X<""> X<//> X<`> X<``> X<<< << >>>
+X<escape sequence> X<escape>
+
While we usually think of quotes as literal values, in Perl they
function as operators, providing various kinds of interpolating and
The following escape sequences are available in constructs that interpolate
and in transliterations.
+X<\t> X<\n> X<\r> X<\f> X<\b> X<\a> X<\e> X<\x> X<\0> X<\c> X<\N>
\t tab (HT, TAB)
\n newline (NL)
The following escape sequences are available in constructs that interpolate
but not in transliterations.
+X<\l> X<\u> X<\L> X<\U> X<\E> X<\Q>
\l lowercase next char
\u uppercase next char
and although they often accept just C<"\012">, they seldom tolerate just
C<"\015">. If you get in the habit of using C<"\n"> for networking,
you may be burned some day.
+X<newline> X<line terminator> X<eol> X<end of line>
+X<\n> X<\r> X<\r\n>
For constructs that do interpolate, variables beginning with "C<$>"
or "C<@>" are interpolated. Subscripted variables such as C<$a[3]> or
variables when used within double quotes.
=head2 Regexp Quote-Like Operators
+X<operator, regexp>
Here are the quote-like operators that apply to pattern
matching and related activities.
=over 8
=item ?PATTERN?
+X<?>
This is just like the C</pattern/> search, except that it matches only
once between calls to the reset() operator. This is a useful
around the year 2168.
=item m/PATTERN/cgimosx
+X<m> X<operator, match>
+X<regexp, options> X<regexp> X<regex, options> X<regex>
+X</c> X</i> X</m> X</o> X</s> X</x>
=item /PATTERN/cgimosx
MiXeD line-noise. That's all!
=item q/STRING/
+X<q> X<quote, double> X<'> X<''>
=item C<'STRING'>
$baz = '\n'; # a two-character string
=item qq/STRING/
+X<qq> X<quote, double> X<"> X<"">
=item "STRING"
$baz = "\n"; # a one-character string
=item qr/STRING/imosx
+X<qr> X</i> X</m> X</o> X</s> X</x>
This operator quotes (and possibly compiles) its I<STRING> as a regular
expression. I<STRING> is interpolated the same way as I<PATTERN>
for a detailed look at the semantics of regular expressions.
=item qx/STRING/
+X<qx> X<`> X<``> X<backtick>
=item `STRING`
See L<"I/O Operators"> for more discussion.
=item qw/STRING/
+X<qw> X<quote, list> X<quote, words>
Evaluates to a list of the words extracted out of STRING, using embedded
whitespace as the word delimiters. It can be understood as being roughly
produces warnings if the STRING contains the "," or the "#" character.
=item s/PATTERN/REPLACEMENT/egimosx
+X<substitute> X<substitution> X<replace> X<regexp, replace>
+X<regexp, substitute> X</e> X</g> X</i> X</m> X</o> X</s> X</x>
Searches a string for a pattern, and if found, replaces that pattern
with the replacement text and returns the number of substitutions
1 while s/\t+/' ' x (length($&)*8 - length($`)%8)/e;
=item tr/SEARCHLIST/REPLACEMENTLIST/cds
+X<tr> X<y> X<transliterate> X</c> X</d> X</s>
=item y/SEARCHLIST/REPLACEMENTLIST/cds
eval "tr/$oldlist/$newlist/, 1" or die $@;
=item <<EOF
+X<here-doc> X<heredoc> X<here-document> X<<< << >>>
A line-oriented form of quoting is based on the shell "here-document"
syntax. Following a C<< << >> you specify a string to terminate
=back
=head2 Gory details of parsing quoted constructs
+X<quote, gory details>
When presented with something that might have several different
interpretations, Perl uses the B<DWIM> (that's "Do What I Mean")
used in parsing.
=item Interpolation
+X<interpolation>
The next step is interpolation in the text obtained, which is now
delimiter-independent. There are four different cases.
which are processed further.
=item Interpolation of regular expressions
+X<regexp, interpolation>
Previous steps were performed during the compilation of Perl code,
but this one happens at run time--although it may be optimized to
switch documented in L<perlrun/"Command Switches">.
=item Optimization of regular expressions
+X<regexp, optimization>
This step is listed for completeness only. Since it does not change
semantics, details of this step are not documented and are subject
=back
=head2 I/O Operators
+X<operator, i/o> X<operator, io> X<io> X<while> X<filehandle>
+X<< <> >> X<@ARGV>
There are several I/O operators you should know about.
backslash. The generalized form of backticks is C<qx//>. (Because
backticks always undergo shell expansion as well, see L<perlsec> for
security concerns.)
+X<qx> X<`> X<``> X<backtick> X<glob>
In scalar context, evaluating a filehandle in angle brackets yields
the next line from that file (the newline, if any, included), or
rather than global.) Additional filehandles may be created with
the open() function, amongst others. See L<perlopentut> and
L<perlfunc/open> for details on this.
+X<stdin> X<stdout> X<sterr>
If a <FILEHANDLE> is used in a context that is looking for
a list, a list comprising all input lines is returned, one line per
@files = glob($files[$i]);
=head2 Constant Folding
+X<constant folding> X<folding>
Like C, Perl does a certain amount of expression evaluation at
compile time whenever it determines that all arguments to an
represents so that the interpreter won't have to.
=head2 No-ops
+X<no-op> X<nop>
Perl doesn't officially have a no-op operator, but the bare constants
C<0> and C<1> are special-cased to not produce a warning in a void
1 while foo();
=head2 Bitwise String Operators
+X<operator, bitwise, string>
Bitstrings of any size may be manipulated by the bitwise operators
(C<~ | & ^>).
in a bit vector.
=head2 Integer Arithmetic
+X<integer>
By default, Perl assumes that it must do most of its arithmetic in
floating point. But by saying
machines.
=head2 Floating-point Arithmetic
+X<floating-point> X<floating point> X<float> X<real>
While C<use integer> provides integer-only arithmetic, there is no
analogous mechanism to provide automatic rounding or truncation to a
need yourself.
=head2 Bigger Numbers
+X<number, arbitrary precision>
The standard Math::BigInt and Math::BigFloat modules provide
variable-precision arithmetic and overloaded operators, although
like "perldoc perlpod".
=head1 NAME
+X<POD> X<plain old documentation>
perlpod - the Plain Old Documentation format
=head2 Ordinary Paragraph
+X<POD, ordinary paragraph>
Most paragraphs in your documentation will be ordinary blocks
of text, like this one. You can simply type in your text without
=head2 Verbatim Paragraph
+X<POD, verbatim paragraph> X<verbatim>
Verbatim paragraphs are usually used for presenting a codeblock or
other text which does not require any special parsing or formatting,
=head2 Command Paragraph
+X<POD, command>
A command paragraph is used for special treatment of whole chunks
of text, usually as headings or parts of lists.
=over
=item C<=head1 I<Heading Text>>
+X<=head1> X<=head2> X<=head3> X<=head4>
+X<head1> X<head2> X<head3> X<head4>
=item C<=head2 I<Heading Text>>
"L<Formatting Codes|/"Formatting Codes">" section, below.
=item C<=over I<indentlevel>>
+X<=over> X<=item> X<=back> X<over> X<item> X<back>
=item C<=item I<stuff...>>
=back
=item C<=cut>
+X<=cut> X<cut>
To end a Pod block, use a blank line,
then a line beginning with "=cut", and a blank
is not technically necessary, but many older Pod processors require it.)
=item C<=pod>
+X<=pod> X<pod>
The "=pod" command by itself doesn't do much of anything, but it
signals to Perl (and Pod formatters) that a Pod block starts here. A
=cut
=item C<=begin I<formatname>>
+X<=begin> X<=end> X<=for> X<begin> X<end> X<for>
=item C<=end I<formatname>>
be for formatting as a footnote).
=item C<=encoding I<encodingname>>
+X<=encoding> X<encoding>
This command is used for declaring the encoding of a document. Most
users won't need this; but if your encoding isn't US-ASCII or Latin-1,
=head2 Formatting Codes
+X<POD, formatting code> X<formatting code>
+X<POD, interior sequence> X<interior sequence>
In ordinary paragraphs and in some command paragraphs, various
formatting codes (a.k.a. "interior sequences") can be used:
=over
=item C<IE<lt>textE<gt>> -- italic text
+X<I> X<< IZ<><> >> X<POD, formatting code, italic> X<italic>
Used for emphasis ("C<be IE<lt>careful!E<gt>>") and parameters
("C<redo IE<lt>LABELE<gt>>")
=item C<BE<lt>textE<gt>> -- bold text
+X<B> X<< BZ<><> >> X<POD, formatting code, bold> X<bold>
Used for switches ("C<perl's BE<lt>-nE<gt> switch>"), programs
("C<some systems provide a BE<lt>chfnE<gt> for that>"),
("C<and that feature is known as BE<lt>autovivificationE<gt>>").
=item C<CE<lt>codeE<gt>> -- code text
+X<C> X<< CZ<><> >> X<POD, formatting code, code> X<code>
Renders code in a typewriter font, or gives some other indication that
this represents program text ("C<CE<lt>gmtime($^T)E<gt>>") or some other
form of computerese ("C<CE<lt>drwxr-xr-xE<gt>>").
=item C<LE<lt>nameE<gt>> -- a hyperlink
+X<L> X<< LZ<><> >> X<POD, formatting code, hyperlink> X<hyperlink>
There are various syntaxes, listed below. In the syntaxes given,
C<text>, C<name>, and C<section> cannot contain the characters
=back
=item C<EE<lt>escapeE<gt>> -- a character escape
+X<E> X<< EZ<><> >> X<POD, formatting code, escape> X<escape>
Very similar to HTML/XML C<&I<foo>;> "entity references":
=back
=item C<FE<lt>filenameE<gt>> -- used for filenames
+X<F> X<< FZ<><> >> X<POD, formatting code, filename> X<filename>
Typically displayed in italics. Example: "C<FE<lt>.cshrcE<gt>>"
=item C<SE<lt>textE<gt>> -- text contains non-breaking spaces
+X<S> X<< SZ<><> >> X<POD, formatting code, non-breaking space>
+X<non-breaking space>
This means that the words in I<text> should not be broken
across lines. Example: S<C<SE<lt>$x ? $y : $zE<gt>>>.
=item C<XE<lt>topic nameE<gt>> -- an index entry
+X<X> X<< XZ<><> >> X<POD, formatting code, index entry> X<index entry>
This is ignored by most formatters, but some may use it for building
indexes. It always renders as empty-string.
Example: C<XE<lt>absolutizing relative URLsE<gt>>
=item C<ZE<lt>E<gt>> -- a null (zero-effect) formatting code
+X<Z> X<< ZZ<><> >> X<POD, formatting code, null> X<null>
This is rarely used. It's one way to get around using an
EE<lt>...E<gt> code sometimes. For example, instead of
whitespace right after the opening delimiter and whitespace right
before the closing delimiter!> For example, the following will
do the trick:
+X<POD, formatting code, escaping with multiple brackets>
C<< $a <=> $b >>
'<' of the opening delimiter, and immediately precedes the first '>'
of the closing delimiter. (The whitespace is ignored.) So the
following will also work:
+X<POD, formatting code, escaping with multiple brackets>
C<<< $a <=> $b >>>
C<<<< $a <=> $b >>>>
Pod::Parser 1.093 or later, or Pod::Tree 1.02 or later.
=head2 The Intent
+X<POD, intent of>
The intent is simplicity of use, not power of expression. Paragraphs
look like paragraphs (block format), so that they stand out
=head2 Embedding Pods in Perl Modules
+X<POD, embedding>
You can embed Pod documentation in your Perl modules and scripts.
Start your documentation with an empty line, a "=head1" command at the
=over
=item *
+X<podchecker> X<POD, validating>
The B<podchecker> command is provided for checking Pod syntax for errors
and warnings. For example, it checks for completely blank lines in
=head1 NAME
+X<regular expression> X<regex> X<regexp>
perlre - Perl regular expressions
=over 4
=item i
+X</i> X<regex, case-insensitive> X<regexp, case-insensitive>
+X<regular expression, case-insensitive>
Do case-insensitive pattern matching.
locale. See L<perllocale>.
=item m
+X</m> X<regex, multiline> X<regexp, multiline> X<regular expression, multiline>
Treat string as multiple lines. That is, change "^" and "$" from matching
the start or end of the string to matching the start or end of any
line anywhere within the string.
=item s
+X</s> X<regex, single-line> X<regexp, single-line>
+X<regular expression, single-line>
Treat string as single line. That is, change "." to match any character
whatsoever, even a newline, which normally it would not match.
and just before newlines within the string.
=item x
+X</x>
Extend your pattern's legibility by permitting whitespace and comments.
pattern delimiter in the comment--perl has no way of knowing you did
not intend to close the pattern early. See the C-comment deletion code
in L<perlop>.
+X</x>
=head2 Regular Expressions
In particular the following metacharacters have their standard I<egrep>-ish
meanings:
+X<metacharacter>
+X<\> X<^> X<.> X<$> X<|> X<(> X<()> X<[> X<[]>
+
\ Quote the next metacharacter
^ Match the beginning of the line
cost of a little more overhead, you can do this by using the /m modifier
on the pattern match operator. (Older programs did this by setting C<$*>,
but this practice has been removed in perl 5.9.)
+X<^> X<$> X</m>
To simplify multi-line substitutions, the "." character never matches a
newline unless you use the C</s> modifier, which in effect tells Perl to pretend
the string is a single line--even if it isn't.
+X<.> X</s>
The following standard quantifiers are recognized:
+X<metacharacter> X<quantifier> X<*> X<+> X<?> X<{n}> X<{n,}> X<{n,m}>
* Match 0 or more times
+ Match 1 or more times
allowing the rest of the pattern to match. If you want it to match the
minimum number of times possible, follow the quantifier with a "?". Note
that the meanings don't change, just the "greediness":
+X<metacharacter> X<greedy> X<greedyness>
+X<?> X<*?> X<+?> X<??> X<{n}?> X<{n,}?> X<{n,m}?>
*? Match 0 or more times
+? Match 1 or more times
Because patterns are processed as double quoted strings, the following
also work:
+X<\t> X<\n> X<\r> X<\f> X<\a> X<\l> X<\u> X<\L> X<\U> X<\E> X<\Q>
+X<\0> X<\c> X<\N> X<\x>
\t tab (HT, TAB)
\n newline (LF, NL)
You'll need to write something like C<m/\Quser\E\@\Qhost/>.
In addition, Perl defines the following:
+X<metacharacter>
+X<\w> X<\W> X<\s> X<\S> X<\d> X<\D> X<\X> X<\p> X<\P> X<\C>
+X<word> X<whitespace>
\w Match a "word" character (alphanumeric plus "_")
\W Match a non-"word" character
"\x{2028}, and "\x{2029}", see L<perlunicode> for more details about
C<\pP>, C<\PP>, and C<\X>, and L<perluniintro> about Unicode in general.
You can define your own C<\p> and C<\P> properties, see L<perlunicode>.
+X<\w> X<\W> X<word>
The POSIX character class syntax
+X<character class>
[:class:]
is also available. The available classes and their backslash
equivalents (if available) are as follows:
+X<character class>
+X<alpha> X<alnum> X<ascii> X<blank> X<cntrl> X<digit> X<graph>
+X<lower> X<print> X<punct> X<space> X<upper> X<word> X<xdigit>
alpha
alnum
The following equivalences to Unicode \p{} constructs and equivalent
backslash character classes (if available), will hold:
+X<character class> X<\p> X<\p{}>
[:...:] \p{...} backslash
=over 4
=item cntrl
+X<cntrl>
Any control character. Usually characters that don't produce output as
such but instead control the terminal somehow: for example newline and
the ord() value of 127 (C<DEL>).
=item graph
+X<graph>
Any alphanumeric or punctuation (special) character.
=item print
+X<print>
Any alphanumeric or punctuation (special) character or the space character.
=item punct
+X<punct>
Any punctuation (special) character.
=item xdigit
+X<xdigit>
Any hexadecimal digit. Though this may feel silly ([0-9A-Fa-f] would
work just fine) it is included for completeness.
You can negate the [::] character classes by prefixing the class name
with a '^'. This is a Perl extension. For example:
+X<character class, negation>
POSIX traditional Unicode
use them will cause an error.
Perl defines the following zero-width assertions:
+X<zero-width assertion> X<assertion> X<regex, zero-width assertion>
+X<regexp, zero-width assertion>
+X<regular expression, zero-width assertion>
+X<\b> X<\B> X<\A> X<\Z> X<\z> X<\G>
\b Match a word boundary
\B Match a non-(word boundary)
"^" and "$" will match at every internal line boundary. To match
the actual end of the string and not ignore an optional trailing
newline, use C<\z>.
+X<\b> X<\A> X<\Z> X<\z> X</m>
The C<\G> assertion can be used to chain global matches (using
C<m//g>), as described in L<perlop/"Regexp Quote-Like Operators">.
is permitted to use it elsewhere, as in C</(?<=\G..)./g>, some
such uses (C</.\G/g>, for example) currently cause problems, and
it is recommended that you avoid such usage for now.
+X<\G>
The bracketing construct C<( ... )> creates capture buffers. To
refer to the digit'th buffer use \<digit> within the
the match. See the warning below about \1 vs $1 for details.)
Referring back to another part of the match is called a
I<backreference>.
+X<regex, capture buffer> X<regexp, capture buffer>
+X<regular expression, capture buffer> X<backreference>
There is no limit to the number of captured substrings that you may
use. However Perl also uses \10, \11, etc. as aliases for \010,
the most-recently closed group (submatch). C<$^N> can be used in
extended patterns (see below), for example to assign a submatch to a
variable.
+X<$+> X<$^N> X<$&> X<$`> X<$'>
The numbered match variables ($1, $2, $3, etc.) and the related punctuation
set (C<$+>, C<$&>, C<$`>, C<$'>, and C<$^N>) are all dynamically scoped
until the end of the enclosing block or until the next successful
match, whichever comes first. (See L<perlsyn/"Compound Statements">.)
+X<$+> X<$^N> X<$&> X<$`> X<$'>
+X<$1> X<$2> X<$3> X<$4> X<$5> X<$6> X<$7> X<$8> X<$9>
+
B<NOTE>: failed matches in Perl do not reset the match variables,
which makes it easier to write code that tests for a series of more
them), once you've used them once, use them at will, because you've
already paid the price. As of 5.005, C<$&> is not so costly as the
other two.
+X<$&> X<$`> X<$'>
Backslashed metacharacters in Perl are alphanumeric, such as C<\b>,
C<\w>, C<\n>. Unlike some other regular expression languages, there
=over 10
=item C<(?#text)>
+X<(?#)>
A comment. The text is ignored. If the C</x> modifier enables
whitespace formatting, a simple C<#> will suffice. Note that Perl closes
C<)> in the comment.
=item C<(?imsx-imsx)>
+X<(?)>
One or more embedded pattern-match modifiers, to be turned on (or
turned off, if preceded by C<->) for the remainder of the pattern or
group.
=item C<(?:pattern)>
+X<(?:)>
=item C<(?imsx-imsx:pattern)>
/(?:(?s-i)more.*than).*million/i
=item C<(?=pattern)>
+X<(?=)> X<look-ahead, positive> X<lookahead, positive>
A zero-width positive look-ahead assertion. For example, C</\w+(?=\t)/>
matches a word followed by a tab, without including the tab in C<$&>.
=item C<(?!pattern)>
+X<(?!)> X<look-ahead, negative> X<lookahead, negative>
A zero-width negative look-ahead assertion. For example C</foo(?!bar)/>
matches any occurrence of "foo" that isn't followed by "bar". Note
For look-behind see below.
=item C<(?<=pattern)>
+X<(?<=)> X<look-behind, positive> X<lookbehind, positive>
A zero-width positive look-behind assertion. For example, C</(?<=\t)\w+/>
matches a word that follows a tab, without including the tab in C<$&>.
Works only for fixed-width look-behind.
=item C<(?<!pattern)>
+X<(?<!)> X<look-behind, negative> X<lookbehind, negative>
A zero-width negative look-behind assertion. For example C</(?<!bar)foo/>
matches any occurrence of "foo" that does not follow "bar". Works
only for fixed-width look-behind.
=item C<(?{ code })>
+X<(?{})> X<regex, code in> X<regexp, code in> X<regular expression, code in>
B<WARNING>: This extended regular expression feature is considered
highly experimental, and may be changed or deleted without notice.
compartment. See L<perlsec> for details about both these mechanisms.
=item C<(??{ code })>
+X<(??{})>
+X<regex, postponed> X<regexp, postponed> X<regular expression, postponed>
+X<regex, recursive> X<regexp, recursive> X<regular expression, recursive>
B<WARNING>: This extended regular expression feature is considered
highly experimental, and may be changed or deleted without notice.
}x;
=item C<< (?>pattern) >>
+X<backtrack> X<backtracking>
B<WARNING>: This extended regular expression feature is considered
highly experimental, and may be changed or deleted without notice.
the above specification of comments.
=item C<(?(condition)yes-pattern|no-pattern)>
+X<(?()>
=item C<(?(condition)yes-pattern)>
=back
=head2 Backtracking
+X<backtrack> X<backtracking>
NOTE: This section presents an abstract approximation of regular
expression behavior. For a more rigorous (and complicated) view of
following match, see L<C<< (?>pattern) >>>.
=head2 Version 8 Regular Expressions
+X<regular expression, version 8> X<regex, version 8> X<regexp, version 8>
In case you're not familiar with the "regular" Version 8 regex
routines, here are the pattern-matching rules not described above.
=head1 NAME
+X<reference> X<pointer> X<data structure> X<structure> X<struct>
perlref - Perl references and nested data structures
The C<*glob> notation is something of a symbolic reference. (Symbolic
references are sometimes called "soft references", but please don't call
them that; references are confusing enough without useless synonyms.)
+X<reference, symbolic> X<reference, soft>
+X<symbolic reference> X<soft reference>
In contrast, hard references are more like hard links in a Unix file
system: They are used to access an underlying object without concern for
what its (other) name is. When the word "reference" is used without an
adjective, as in the following paragraph, it is usually talking about a
hard reference.
+X<reference, hard> X<hard reference>
References are easy to use in Perl. There is just one overriding
principle: Perl does no implicit referencing or dereferencing. When a
tell it explicitly to do so, by dereferencing it.
=head2 Making References
+X<reference, creation> X<referencing>
References can be created in several ways.
=over 4
=item 1.
+X<\> X<backslash>
By using the backslash operator on a variable, subroutine, or value.
(This works much like the & (address-of) operator in C.)
you can still use type globs and globrefs as though they were IO handles.
=item 2.
+X<array, anonymous> X<[> X<[]> X<square bracket>
+X<bracket, square> X<arrayref> X<array reference> X<reference, array>
A reference to an anonymous array can be created using square
brackets:
strings rather than full-fledged scalars).
=item 3.
+X<hash, anonymous> X<{> X<{}> X<curly bracket>
+X<bracket, curly> X<brace> X<hashref> X<hash reference> X<reference, hash>
A reference to an anonymous hash can be created using curly
brackets:
the expression to mean either the HASH reference, or the BLOCK.
=item 4.
+X<subroutine, anonymous> X<subroutine, reference> X<reference, subroutine>
+X<scope, lexical> X<closure> X<lexical> X<lexical scope>
A reference to an anonymous subroutine can be created by using
C<sub> without a subname:
that most Perl programmers need trouble themselves about to begin with.
=item 5.
+X<constructor> X<new>
References are often returned by special subroutines called constructors.
Perl objects are just references to a special type of object that happens to know
-borderwidth => 2)
=item 6.
+X<autovivification>
References of the appropriate type can spring into existence if you
dereference them in a context that assumes they exist. Because we haven't
talked about dereferencing yet, we can't show you any examples yet.
=item 7.
+X<*foo{THING}> X<*>
A reference can be created by using a special syntax, lovingly known as
the *foo{THING} syntax. *foo{THING} returns a reference to the THING
=back
=head2 Using References
+X<reference, use> X<dereferencing> X<dereference>
That's it for creating references. By now you're probably dying to
know how to use references to get back to your long-lost data. There
print $$$$refrefref;
=item 2.
+X<${}> X<@{}> X<%{}>
Anywhere you'd put an identifier (or chain of identifiers) as part of a
variable or subroutine name, you can replace the identifier with a
it's presumably referencing. That would be case 3.
=item 3.
+X<autovivification> X<< -> >> X<arrow>
Subroutine calls and lookups of individual array elements arise often
enough that it gets cumbersome to use method 2. As a form of
to grow its arrays on demand. Perl does.
=item 4.
+X<encapsulation>
If a reference happens to be a reference to an object, then there are
probably methods to access the things referred to, and you should probably
integer representing its storage location in memory. The only
useful thing to be done with this is to compare two references
numerically to see whether they refer to the same location.
+X<reference, numeric context>
if ($ref1 == $ref2) { # cheap numeric compare of references
print "refs 1 and 2 refer to the same thing\n";
as the numeric address expressed in hex. The ref() operator returns
just the type of thing the reference is pointing to, without the
address. See L<perlfunc/ref> for details and examples of its use.
+X<reference, string context>
The bless() operator may be used to associate the object a reference
points to with a package functioning as an object class. See L<perlobj>.
print "That yields @{[$n + 5]} widgets\n";
=head2 Symbolic references
+X<reference, symbolic> X<reference, soft>
+X<symbolic reference> X<soft reference>
We said that references spring into existence as necessary if they are
undefined, but we didn't say what happens if a value used as a
string is effectively quoted.
=head2 Pseudo-hashes: Using an array as a hash
+X<pseudo-hash> X<pseudo hash> X<pseudohash>
Pseudo-hashes have been removed from Perl. The 'fields' pragma
remains available.
=head2 Function Templates
+X<scope, lexical> X<closure> X<lexical> X<lexical scope>
+X<subroutine, nested> X<sub, nested> X<subroutine, local> X<sub, local>
As explained above, an anonymous function with access to the lexical
variables visible when that function was compiled, creates a closure. It
function, something not normally supported in Perl.
=head1 WARNING
+X<reference, string context> X<reference, use as hash key>
You may not (usefully) use a reference as the key to a hash. It will be
converted into a string:
C<exit(0)> is provided to indicate successful completion.
=head2 #! and quoting on non-Unix systems
+X<hashbang> X<#!>
Unix's #! technique can be simulated on other systems:
There is no general solution to all of this. It's just a mess.
=head2 Location of Perl
+X<perl, location of interpreter>
It may seem obvious to say, but Perl is useful only when users can
easily find it. When possible, it's good for both F</usr/bin/perl>
use 5.005_54;
=head2 Command Switches
+X<perl, command switches> X<command switches>
As with all standard commands, a single-character switch may be
clustered with the following switch, if any.
=over 5
=item B<-0>[I<octal/hexadecimal>]
+X<-0> X<$/>
specifies the input record separator (C<$/>) as an octal or
hexadecimal number. If there are no digits, the null character is the
consists of hexadecimal digits.)
=item B<-A[I<module>][=I<assertions>]>
+X<-A>
Activates the assertions given after the equal sign as a comma-separated
list of assertion names or regular expressions. If no assertion name
See L<assertions> and L<assertions::activate>.
=item B<-a>
+X<-a> X<autosplit>
turns on autosplit mode when used with a B<-n> or B<-p>. An implicit
split command to the @F array is done as the first thing inside the
An alternate delimiter may be specified using B<-F>.
=item B<-C [I<number/list>]>
+X<-C>
The C<-C> flag controls some Unicode of the Perl Unicode features.
switch was therefore "recycled".)
=item B<-c>
+X<-c>
causes Perl to check the syntax of the program and then exit without
executing it. Actually, it I<will> execute C<BEGIN>, C<CHECK>, and
be skipped.
=item B<-d>
+X<-d> X<-dt>
=item B<-dt>
will be used in the code being debugged.
=item B<-d:>I<foo[=bar,baz]>
+X<-d> X<-dt>
=item B<-dt:>I<foo[=bar,baz]>
See L<perldebug>.
=item B<-D>I<letters>
+X<-D> X<DEBUGGING> X<-DDEBUGGING>
=item B<-D>I<number>
See L<perldebug> for details and variations.
=item B<-e> I<commandline>
+X<-e>
may be used to enter one line of program. If B<-e> is given, Perl
will not look for a filename in the argument list. Multiple B<-e>
to use semicolons where you would in a normal program.
=item B<-f>
+X<-f>
Disable executing F<$Config{siteperl}/sitecustomize.pl> at
startup.
modules in non-standard locations.
=item B<-F>I<pattern>
+X<-F>
specifies the pattern to split on if B<-a> is also in effect. The
pattern may be surrounded by C<//>, C<"">, or C<''>, otherwise it will be
put in single quotes. You can't use literal whitespace in the pattern.
=item B<-h>
+X<-h>
prints a summary of the options.
=item B<-i>[I<extension>]
+X<-i> X<in-place>
specifies that files processed by the C<E<lt>E<gt>> construct are to be
edited in-place. It does this by renaming the input file, opening the
proceeds from STDIN to STDOUT as might be expected.
=item B<-I>I<directory>
+X<-I> X<@INC>
Directories specified by B<-I> are prepended to the search path for
modules (C<@INC>), and also tells the C preprocessor where to search for
searches /usr/include and /usr/lib/perl.
=item B<-l>[I<octnum>]
+X<-l> X<$/> X<$\>
enables automatic line-ending processing. It has two separate
effects. First, it automatically chomps C<$/> (the input record
This sets C<$\> to newline and then sets C<$/> to the null character.
=item B<-m>[B<->]I<module>
+X<-m> X<-M>
=item B<-M>[B<->]I<module>
could happen for example if Foo inherits from Exporter.)
=item B<-n>
+X<-n>
causes Perl to assume the following loop around your program, which
makes it iterate over filename arguments somewhat like B<sed -n> or
the implicit program loop, just as in B<awk>.
=item B<-p>
+X<-p>
causes Perl to assume the following loop around your program, which
makes it iterate over filename arguments somewhat like B<sed>:
the implicit loop, just as in B<awk>.
=item B<-P>
+X<-P>
B<NOTE: Use of -P is strongly discouraged because of its inherent
problems, including poor portability.>
=back
=item B<-s>
+X<-s>
enables rudimentary switch parsing for switches on the command
line after the program name but before any filename arguments (or before
warnings enabled you may get a lot of spurious "used only once" warnings.
=item B<-S>
+X<-S>
makes Perl use the PATH environment variable to search for the
program (unless the name of the program contains directory separators).
program will be searched for strictly on the PATH.
=item B<-t>
+X<-t>
Like B<-T>, but taint checks will issue warnings rather than fatal
errors. These warnings can be controlled normally with C<no warnings
always use the real B<-T>.
=item B<-T>
+X<-T>
forces "taint" checks to be turned on so you can test them. Ordinarily
these checks are done only when running setuid or setgid. It's a
that construct.
=item B<-u>
+X<-u>
This obsolete switch causes Perl to dump core after compiling your
program. You can then in theory take this core dump and turn it
for details.
=item B<-U>
+X<-U>
allows Perl to do unsafe operations. Currently the only "unsafe"
operations are the unlinking of directories while running as superuser,
taint-check warnings.
=item B<-v>
+X<-v>
prints the version and patchlevel of your perl executable.
=item B<-V>
+X<-V>
prints summary of the major perl configuration values and the current
values of @INC.
building_on 'linux' '5' '1' '9' now
=item B<-w>
+X<-w>
prints warnings about dubious constructs, such as variable names
that are mentioned only once and scalar variables that are used
of warnings; see L<warnings> or L<perllexwarn>.
=item B<-W>
+X<-W>
Enables all warnings regardless of C<no warnings> or C<$^W>.
See L<perllexwarn>.
=item B<-X>
+X<-X>
Disables all warnings regardless of C<use warnings> or C<$^W>.
See L<perllexwarn>.
=item B<-x>
+X<-x>
=item B<-x> I<directory>
=back
=head1 ENVIRONMENT
+X<perl, environment variables>
=over 12
=item HOME
+X<HOME>
Used if chdir has no argument.
=item LOGDIR
+X<LOGDIR>
Used if chdir has no argument and HOME is not set.
=item PATH
+X<PATH>
Used in executing subprocesses, and in finding the program if B<-S> is
used.
=item PERL5LIB
+X<PERL5LIB>
A list of directories in which to look for Perl library
files before looking in the standard library and the current
use lib "/my/directory";
=item PERL5OPT
+X<PERL5OPT>
Command-line options (switches). Switches in this variable are taken
as if they were on every Perl command line. Only the B<-[CDIMUdmtwA]>
enabled, and any subsequent options ignored.
=item PERLIO
+X<PERLIO>
A space (or colon) separated list of PerlIO layers. If perl is built
to use PerlIO system for IO (the default) these layers effect perl's IO.
=over 8
=item :bytes
+X<:bytes>
A pseudolayer that turns I<off> the C<:utf8> flag for the layer below.
Unlikely to be useful on its own in the global PERLIO environment variable.
You perhaps were thinking of C<:crlf:bytes> or C<:perlio:bytes>.
=item :crlf
+X<:crlf>
A layer which does CRLF to "\n" translation distinguishing "text" and
"binary" files in the manner of MS-DOS and similar operating systems.
as being an end-of-file marker.)
=item :mmap
+X<:mmap>
A layer which implements "reading" of files by using C<mmap()> to
make (whole) file appear in the process's address space, and then
using that as PerlIO's "buffer".
=item :perlio
+X<:perlio>
This is a re-implementation of "stdio-like" buffering written as a
PerlIO "layer". As such it will call whatever layer is below it for
its operations (typically C<:unix>).
=item :pop
+X<:pop>
An experimental pseudolayer that removes the topmost layer.
Use with the same care as is reserved for nitroglycerin.
=item :raw
+X<:raw>
A pseudolayer that manipulates other layers. Applying the C<:raw>
layer is equivalent to calling C<binmode($fh)>. It makes the stream
binary nature of the stream are also removed or disabled.
=item :stdio
+X<:stdio>
This layer provides PerlIO interface by wrapping system's ANSI C "stdio"
library calls. The layer provides both buffering and IO.
to do that.
=item :unix
+X<:unix>
Low level layer which calls C<read>, C<write> and C<lseek> etc.
=item :utf8
+X<:utf8>
A pseudolayer that turns on a flag on the layer below to tell perl
that output should be in utf8 and that input should be regarded as
use C<:bytes> layer.)
=item :win32
+X<:win32>
On Win32 platforms this I<experimental> layer uses native "handle" IO
rather than unix-like numeric file descriptor layer. Known to be
the default under Win32.
=item PERLIO_DEBUG
+X<PERLIO_DEBUG>
If set to the name of a file or device then certain operations of PerlIO
sub-system will be logged to that file (opened as append). Typical uses
with B<-T>.
=item PERLLIB
+X<PERLLIB>
A list of directories in which to look for Perl library
files before looking in the standard library and the current directory.
If PERL5LIB is defined, PERLLIB is not used.
=item PERL5DB
+X<PERL5DB>
The command used to load the debugger code. The default is:
BEGIN { require 'perl5db.pl' }
=item PERL5DB_THREADED
+X<PERL5DB_THREADED>
If set to a true value, indicates to the debugger that the code being
debugged uses threads.
=item PERL5SHELL (specific to the Win32 port)
+X<PERL5SHELL>
May be set to an alternative shell that perl must use internally for
executing "backtick" commands or system(). Default is C<cmd.exe /x/d/c>
look in COMSPEC to find a shell fit for interactive use).
=item PERL_ALLOW_NON_IFS_LSP (specific to the Win32 port)
+X<PERL_ALLOW_NON_IFS_LSP>
Set to 1 to allow the use of non-IFS compatible LSP's.
Perl normally searches for an IFS-compatible LSP because this is required
requiring IFS compatibility to work).
=item PERL_DEBUG_MSTATS
+X<PERL_DEBUG_MSTATS>
Relevant only if perl is compiled with the malloc included with the perl
distribution (that is, if C<perl -V:d_mymalloc> is 'define').
after compilation.
=item PERL_DESTRUCT_LEVEL
+X<PERL_DESTRUCT_LEVEL>
Relevant only if your perl executable was built with B<-DDEBUGGING>,
this controls the behavior of global destruction of objects and other
references. See L<perlhack/PERL_DESTRUCT_LEVEL> for more information.
=item PERL_DL_NONLAZY
+X<PERL_DL_NONLAZY>
Set to one to have perl resolve B<all> undefined symbols when it loads
a dynamic library. The default behaviour is to resolve symbols when
names even if the test suite doesn't call it.
=item PERL_ENCODING
+X<PERL_ENCODING>
If using the C<encoding> pragma without an explicit encoding name, the
PERL_ENCODING environment variable is consulted for an encoding name.
=item PERL_HASH_SEED
+X<PERL_HASH_SEED>
(Since Perl 5.8.1.) Used to randomise Perl's internal hash function.
To emulate the pre-5.8.1 behaviour, set to an integer (zero means
L</PERL_HASH_SEED_DEBUG> for more information.
=item PERL_HASH_SEED_DEBUG
+X<PERL_HASH_SEED_DEBUG>
(Since Perl 5.8.1.) Set to one to display (to STDERR) the value of
the hash seed at the beginning of execution. This, combined with
See also hash_seed() of L<Hash::Util>.
=item PERL_ROOT (specific to the VMS port)
+X<PERL_ROOT>
A translation concealed rooted logical name that contains perl and the
logical device for the @INC path on VMS only. Other logical names that
L<perlvms> and in F<README.vms> in the Perl source distribution.
=item PERL_SIGNALS
+X<PERL_SIGNALS>
In Perls 5.8.1 and later. If set to C<unsafe> the pre-Perl-5.8.0
signals behaviour (immediate but unsafe) is restored. If set to
See L<perlipc/"Deferred Signals (Safe Signals)">.
=item PERL_UNICODE
+X<PERL_UNICODE>
Equivalent to the B<-C> command-line switch. Note that this is not
a boolean variable-- setting this to C<"1"> is not the right way to
switch for more information.
=item SYS$LOGIN (specific to the VMS port)
+X<SYS$LOGIN>
Used if chdir has no argument and HOME and LOGDIR are not set.
=head1 NAME
+X<subroutine> X<function>
perlsub - Perl subroutines
=head1 SYNOPSIS
To declare subroutines:
+X<subroutine, declaration> X<sub>
sub NAME; # A "forward" declaration.
sub NAME(PROTO); # ditto, but with prototypes
sub NAME(PROTO) : ATTRS BLOCK # with prototypes and attributes
To define an anonymous subroutine at runtime:
+X<subroutine, anonymous>
$subref = sub BLOCK; # no proto
$subref = sub (PROTO) BLOCK; # with proto
$subref = sub (PROTO) : ATTRS BLOCK; # with proto and attributes
To import subroutines:
+X<import>
use MODULE qw(NAME1 NAME2 NAME3);
To call subroutines:
+X<subroutine, call> X<call>
NAME(LIST); # & is optional with parentheses.
NAME LIST; # Parentheses optional if predeclared/imported.
contain as many or as few scalar elements as you'd like. (Often a
function without an explicit return statement is called a subroutine, but
there's really no difference from Perl's perspective.)
+X<subroutine, parameter> X<parameter>
Any arguments passed in show up in the array C<@_>. Therefore, if
you called a function with two arguments, those would be stored in
created the element whether or not the element was assigned to.)
Assigning to the whole array C<@_> removes that aliasing, and does
not update any arguments.
+X<subroutine, argument> X<argument> X<@_>
The return value of a subroutine is the value of the last expression
evaluated by that sub, or the empty list in the case of an empty sub.
value in scalar context, or nothing in void context. If you return
one or more aggregates (arrays and hashes), these will be flattened
together into one large indistinguishable list.
+X<subroutine, return value> X<return value> X<return>
Perl does not have named formal parameters. In practice all you
do is assign to a C<my()> list of these. Variables that aren't
and L<"Temporary Values via local()">. To create protected
environments for a set of functions in a separate package (and
probably a separate file), see L<perlmod/"Packages">.
+X<formal parameter> X<parameter, formal>
Example:
of turning call-by-reference into call-by-value. Otherwise a
function is free to do in-place modifications of C<@_> and change
its caller's values.
+X<call-by-reference> X<call-by-value>
upcase_in($v1, $v2); # this changes $v1 and $v2
sub upcase_in {
You aren't allowed to modify constants in this way, of course. If an
argument were actually literal and you tried to change it, you'd take a
(presumably fatal) exception. For example, this won't work:
+X<call-by-reference> X<call-by-value>
upcase_in("frederick");
reference using the C<&$subref()> or C<&{$subref}()> constructs,
although the C<< $subref->() >> notation solves that problem.
See L<perlref> for more about all that.
+X<&>
Subroutines may be called recursively. If a subroutine is called
using the C<&> form, the argument list is optional, and if omitted,
no C<@_> array is set up for the subroutine: the C<@_> array at the
time of the call is visible to subroutine instead. This is an
efficiency mechanism that new users may wish to avoid.
+X<recursion>
&foo(1,2,3); # pass three arguments
foo(1,2,3); # the same
disables any prototype checking on arguments you do provide. This
is partly for historical reasons, and partly for having a convenient way
to cheat if you know what you're doing. See L<Prototypes> below.
+X<&>
Subroutines whose names are in all upper case are reserved to the Perl
core, as are modules whose names are in all lower case. A subroutine in
L<perlmod/"BEGIN, CHECK, INIT and END">
=head2 Private Variables via my()
+X<my> X<variable, lexical> X<lexical> X<lexical variable> X<scope, lexical>
+X<lexical scope> X<attributes, my>
Synopsis:
world, including any called subroutines. This is true if it's the
same subroutine called from itself or elsewhere--every call gets
its own copy.
+X<local>
This doesn't mean that a C<my> variable declared in a statically
enclosing lexical scope would be invisible. Only dynamic scopes
An C<eval()>, however, can see lexical variables of the scope it is
being evaluated in, so long as the names aren't hidden by declarations within
the C<eval()> itself. See L<perlref>.
+X<eval, scope of>
The parameter list to my() may be assigned to if desired, which allows you
to initialize your variables. (If no initializer is given for a
prefixed with the keyword C<my>, or if there is already a lexical
by that name in scope, then a new lexical is created instead. Thus
in the loop
+X<foreach> X<for>
for my $i (1, 2, 3) {
some_function();
the scope of $i extends to the end of the loop, but not beyond it,
rendering the value of $i inaccessible within C<some_function()>.
+X<foreach> X<for>
Some users may wish to encourage the use of lexically scoped variables.
As an aid to catching implicit uses to package variables,
this.
=head2 Persistent Private Variables
+X<static> X<variable, persistent> X<variable, static> X<closure>
Just because a lexical variable is lexically (also called statically)
scoped to its enclosing block, C<eval>, or C<do> FILE, this doesn't mean that
to create private variables that the whole module can see.
=head2 Temporary Values via local()
+X<local> X<scope, dynamic> X<dynamic scope> X<variable, local>
+X<variable, temporary>
B<WARNING>: In general, you should be using C<my> instead of C<local>, because
it's faster and safer. Exceptions to this include the global punctuation
variables outside the loop.
=head3 Grammatical note on local()
+X<local, context>
A C<local> is simply a modifier on an lvalue expression. When you assign to
a C<local>ized variable, the C<local> doesn't change whether its list is viewed
supplies a scalar context.
=head3 Localization of special variables
+X<local, special variable>
If you localize a special variable, you'll be giving a new value to it,
but its magic won't go away. That means that all side-effects related
or hashes (localising individual elements is still okay).
See L<perl58delta/"Localising Tied Arrays and Hashes Is Broken"> for more
details.
+X<local, tie>
=head3 Localization of globs
+X<local, glob> X<glob>
The construct
with C<my $_>), which avoids completely this problem.
=head3 Localization of elements of composite types
+X<local, composite type element> X<local, array element> X<local, hash element>
It's also worth taking a moment to explain what happens when you
C<local>ize a member of a composite type (i.e. an array or hash element).
types is subject to change in future.
=head2 Lvalue subroutines
+X<lvalue> X<subroutine, lvalue>
B<WARNING>: Lvalue subroutines are still experimental and the
implementation may change in future versions of Perl.
=back
=head2 Passing Symbol Table Entries (typeglobs)
+X<typeglob> X<*>
B<WARNING>: The mechanism described in this section was originally
the only way to simulate pass-by-reference in older versions of
L<perldata/"Typeglobs and Filehandles">.
=head2 When to Still Use local()
+X<local> X<variable, local>
Despite the existence of C<my>, there are still three places where the
C<local> operator still shines. In fact, in these three places, you
=back
=head2 Pass by Reference
+X<pass by reference> X<pass-by-reference> X<reference>
If you want to pass more than one array or hash into a function--or
return them from it--and have them maintain their integrity, then
}
=head2 Prototypes
+X<prototype> X<subroutine, prototype>
Perl supports a very limited kind of compile-time argument checking
using function prototyping. If you declare
The interesting thing about C<&> is that you can generate new syntax with it,
provided it's in the initial position:
+X<&>
sub try (&@) {
my($try,$catch) = @_;
is this sounding a little Lispish? (Never mind.))))
And here's a reimplementation of the Perl C<grep> operator:
+X<grep>
sub mygrep (&@) {
my $code = shift;
to make the world a better place.
=head2 Constant Functions
+X<constant>
Functions with a prototype of C<()> are potential candidates for
inlining. If the result after optimization and constant folding
}
=head2 Overriding Built-in Functions
+X<built-in> X<override> X<CORE> X<CORE::GLOBAL>
Many built-in functions may be overridden, though this should be tried
only occasionally and for good reason. Typically this might be
Finally, some built-ins (e.g. C<exists> or C<grep>) can't be overridden.
=head2 Autoloading
+X<autoloading> X<AUTOLOAD>
If you call a subroutine that is undefined, you would ordinarily
get an immediate, fatal error complaining that the subroutine doesn't
functions to Perl code in L<perlxs>.
=head2 Subroutine Attributes
+X<attribute> X<subroutine, attribute> X<attrs>
A subroutine declaration or definition may have a list of attributes
associated with it. If such an attribute list is present, it is
=head1 NAME
+X<syntax>
perlsyn - Perl syntax
see L<perltrap> for information about how they differ.
=head2 Declarations
+X<declaration> X<undef> X<undefined> X<uninitialized>
The only things you need to declare in Perl are report formats and
subroutines (and sometimes not even subroutines). A variable holds
Declaring a subroutine allows a subroutine name to be used as if it were a
list operator from that point forward in the program. You can declare a
subroutine without defining it by saying C<sub name>, thus:
+X<subroutine, declaration>
sub myname;
$me = myname $0 or die "can't get myname";
has both compile-time and run-time effects.
=head2 Comments
+X<comment> X<#>
Text from a C<"#"> character until the end of the line is a comment,
and is ignored. Exceptions include C<"#"> inside a string or regular
expression.
=head2 Simple Statements
+X<statement> X<semicolon> X<expression> X<;>
The only kind of simple statement is an expression evaluated for its
side effects. Every simple statement must be terminated with a
as the last item in a statement.
=head2 Truth and Falsehood
+X<truth> X<falsehood> X<true> X<false> X<!> X<not> X<negation> X<0>
The number 0, the strings C<'0'> and C<''>, the empty list C<()>, and
C<undef> are all false in a boolean context. All other values are true.
is treated as 0.
=head2 Statement Modifiers
+X<statement modifier> X<modifier> X<if> X<unless> X<while>
+X<until> X<foreach> X<for>
Any simple statement may optionally be followed by a I<SINGLE> modifier,
just before the terminating semicolon (or block ending). The possible
loop labels. Sorry. You can always put another block inside of it
(for C<next>) or around it (for C<last>) to do that sort of thing.
For C<next>, just double the braces:
+X<next> X<last> X<redo>
do {{
next if $x == $y;
}} until $x++ > $z;
For C<last>, you have to be more elaborate:
+X<last>
LOOP: {
do {
previously assigned value, or possibly anything else. Don't rely on
it. Future versions of perl might do something different from the
version of perl you try it out on. Here be dragons.
+X<my>
=head2 Compound Statements
+X<statement, compound> X<block> X<bracket, curly> X<curly bracket> X<brace>
+X<{> X<}> X<if> X<unless> X<while> X<until> X<foreach> X<for> X<continue>
In Perl, a sequence of statements that defines a scope is called a block.
Sometimes a block is delimited by the file containing it (in the case
the C<next> statement.
=head2 Loop Control
+X<loop control> X<loop, control> X<next> X<last> X<redo> X<continue>
The C<next> command starts the next iteration of the loop:
available. Replace any occurrence of C<if BLOCK> by C<if (do BLOCK)>.
=head2 For Loops
+X<for> X<foreach>
Perl's C-style C<for> loop works like the corresponding C<while> loop;
that means that this:
in the initialization section of the C<for>, the lexical scope of
those variables is exactly the C<for> loop (the body of the loop
and the control sections).
+X<my>
Besides the normal array index looping, C<for> can lend itself
to many other interesting applications. Here's one that avoids the
problem you get into if you explicitly test for end-of-file on
an interactive file descriptor causing your program to appear to
hang.
+X<eof> X<end-of-file> X<end of file>
$on_a_tty = -t STDIN && -t STDOUT;
sub prompt { print "yes? " if $on_a_tty }
Using C<readline> (or the operator form, C<< <EXPR> >>) as the
conditional of a C<for> loop is shorthand for the following. This
behaviour is the same as a C<while> loop conditional.
+X<readline> X<< <> >>
for ( prompt(); defined( $_ = <STDIN> ); prompt() ) {
# do something
}
=head2 Foreach Loops
+X<for> X<foreach>
The C<foreach> loop iterates over a normal list value and sets the
variable VAR to be each element of the list in turn. If the variable
that variable instead of the global one, but it's still localized to
the loop. This implicit localisation occurs I<only> in a C<foreach>
loop.
+X<my> X<local>
The C<foreach> keyword is actually a synonym for the C<for> keyword, so
you can use C<foreach> for readability or C<for> for brevity. (Or because
the Bourne shell is more familiar to you than I<csh>, so writing C<for>
comes more naturally.) If VAR is omitted, C<$_> is set to each value.
+X<$_>
If any element of LIST is an lvalue, you can modify it by modifying
VAR inside the loop. Conversely, if any element of LIST is NOT an
lvalue, any attempt to modify that element will fail. In other words,
the C<foreach> loop index variable is an implicit alias for each item
in the list that you're looping over.
+X<alias>
If any part of LIST is an array, C<foreach> will get very confused if
you add or remove elements within the loop body, for example with
C<splice>. So don't do that.
+X<splice>
C<foreach> probably won't do what you expect if VAR is a tied or other
special variable. Don't do that either.
equivalent C<for> loop.
=head2 Basic BLOCKs and Switch Statements
+X<switch> X<block> X<case>
A BLOCK by itself (labeled or not) is semantically equivalent to a
loop that executes once. Thus you can use any of the loop control
instead of synthesizing a C<switch> statement.
=head2 Goto
+X<goto>
Although not for the faint of heart, Perl does support a C<goto>
statement. There are three forms: C<goto>-LABEL, C<goto>-EXPR, and
C<eval{}> and die() for exception processing can also be a prudent approach.
=head2 PODs: Embedded Documentation
+X<POD> X<documentation>
Perl has a mechanism for intermixing documentation with source code.
While it's expecting the beginning of a new statement, if the compiler
of code.
=head2 Plain Old Comments (Not!)
+X<comment> X<line> X<#> X<preprocessor> X<eval>
Perl can process line directives, much like the C preprocessor. Using
this, one can control Perl's idea of filenames and line numbers in
=head1 NAME
+X<tie>
perltie - how to hide an object class in a simple variable
for you--you need to do that explicitly yourself.
=head2 Tying Scalars
+X<scalar, tying>
A class implementing a tied scalar should define the following methods:
TIESCALAR, FETCH, STORE, and possibly UNTIE and/or DESTROY.
=over 4
=item TIESCALAR classname, LIST
+X<TIESCALAR>
This is the constructor for the class. That means it is
expected to return a blessed reference to a new scalar
variable C<$^W> to see whether to emit a bit of noise anyway.
=item FETCH this
+X<FETCH>
This method will be triggered every time the tied variable is accessed
(read). It takes no arguments beyond its self reference, which is the
probably the right thing to do.
=item STORE this, value
+X<STORE>
This method will be triggered every time the tied variable is set
(assigned). Beyond its self reference, it also expects one (and only one)
}
=item UNTIE this
+X<UNTIE>
This method will be triggered when the C<untie> occurs. This can be useful
if the class needs to know when no further calls will be made. (Except DESTROY
of course.) See L<The C<untie> Gotcha> below for more details.
=item DESTROY this
+X<DESTROY>
This method will be triggered when the tied variable needs to be destructed.
As with other object classes, such a method is seldom necessary, because Perl
TIESCALAR classes are certainly possible.
=head2 Tying Arrays
+X<array, tying>
A class implementing a tied ordinary array should define the following
methods: TIEARRAY, FETCH, STORE, FETCHSIZE, STORESIZE and perhaps UNTIE and/or DESTROY.
=over 4
=item TIEARRAY classname, LIST
+X<TIEARRAY>
This is the constructor for the class. That means it is expected to
return a blessed reference through which the new array (probably an
}
=item FETCH this, index
+X<FETCH>
This method will be triggered every time an individual element the tied array
is accessed (read). It takes one argument beyond its self reference: the
to keep them at simply one tie type per class.
=item STORE this, index, value
+X<STORE>
This method will be triggered every time an element in the tied array is set
(written). It takes two arguments beyond its self reference: the index at
Negative indexes are treated the same as with FETCH.
=item FETCHSIZE this
+X<FETCHSIZE>
Returns the total number of items in the tied array associated with
object I<this>. (Equivalent to C<scalar(@array)>). For example:
}
=item STORESIZE this, count
+X<STORESIZE>
Sets the total number of items in the tied array associated with
object I<this> to be I<count>. If this makes the array larger then
}
=item EXTEND this, count
+X<EXTEND>
Informative call that array is likely to grow to have I<count> entries.
Can be used to optimize allocation. This method need do nothing.
}
=item EXISTS this, key
+X<EXISTS>
Verify that the element at index I<key> exists in the tied array I<this>.
}
=item DELETE this, key
+X<DELETE>
Delete the element at index I<key> from the tied array I<this>.
}
=item CLEAR this
+X<CLEAR>
Clear (remove, delete, ...) all values from the tied array associated with
object I<this>. For example:
}
=item PUSH this, LIST
+X<PUSH>
Append elements of I<LIST> to the array. For example:
}
=item POP this
+X<POP>
Remove last element of the array and return it. For example:
}
=item SHIFT this
+X<SHIFT>
Remove the first element of the array (shifting other elements down)
and return it. For example:
}
=item UNSHIFT this, LIST
+X<UNSHIFT>
Insert LIST elements at the beginning of the array, moving existing elements
up to make room. For example:
}
=item SPLICE this, offset, length, LIST
+X<SPLICE>
Perform the equivalent of C<splice> on the array.
}
=item UNTIE this
+X<UNTIE>
Will be called when C<untie> happens. (See L<The C<untie> Gotcha> below.)
=item DESTROY this
+X<DESTROY>
This method will be triggered when the tied variable needs to be destructed.
As with the scalar tie class, this is almost never needed in a
=back
=head2 Tying Hashes
+X<hash, tying>
Hashes were the first Perl data type to be tied (see dbmopen()). A class
implementing a tied hash should define the following methods: TIEHASH is
=over 4
=item TIEHASH classname, LIST
+X<TIEHASH>
This is the constructor for the class. That means it is expected to
return a blessed reference through which the new object (probably but not
have been testing the wrong file.
=item FETCH this, key
+X<FETCH>
This method will be triggered every time an element in the tied hash is
accessed (read). It takes one argument beyond its self reference: the key
not that concerned.
=item STORE this, key, value
+X<STORE>
This method will be triggered every time an element in the tied hash is set
(written). It takes two arguments beyond its self reference: the index at
}
=item DELETE this, key
+X<DELETE>
This method is triggered when we remove an element from the hash,
typically by using the delete() function. Again, we'll
the caller whether the file was successfully deleted.
=item CLEAR this
+X<CLEAR>
This method is triggered when the whole hash is to be cleared, usually by
assigning the empty list to it.
}
=item EXISTS this, key
+X<EXISTS>
This method is triggered when the user uses the exists() function
on a particular hash. In our example, we'll look at the C<{LIST}>
}
=item FIRSTKEY this
+X<FIRSTKEY>
This method will be triggered when the user is going
to iterate through the hash, such as via a keys() or each()
}
=item NEXTKEY this, lastkey
+X<NEXTKEY>
This method gets triggered during a keys() or each() iteration. It has a
second argument which is the last key that had been accessed. This is
}
=item SCALAR this
+X<SCALAR>
This is called when the hash is evaluated in scalar context. In order
to mimic the behaviour of untied hashes, this method should return a
}
=item UNTIE this
+X<UNTIE>
This is called when C<untie> occurs. See L<The C<untie> Gotcha> below.
=item DESTROY this
+X<DESTROY>
This method is triggered when a tied hash is about to go out of
scope. You don't really need it unless you're trying to add debugging
untie(%HIST);
=head2 Tying FileHandles
+X<filehandle, tying>
This is partially implemented now.
=over 4
=item TIEHANDLE classname, LIST
+X<TIEHANDLE>
This is the constructor for the class. That means it is expected to
return a blessed reference of some sort. The reference can be used to
sub TIEHANDLE { print "<shout>\n"; my $i; bless \$i, shift }
=item WRITE this, LIST
+X<WRITE>
This method will be called when the handle is written to via the
C<syswrite> function.
}
=item PRINT this, LIST
+X<PRINT>
This method will be triggered every time the tied handle is printed to
with the C<print()> function.
sub PRINT { $r = shift; $$r++; print join($,,map(uc($_),@_)),$\ }
=item PRINTF this, LIST
+X<PRINTF>
This method will be triggered every time the tied handle is printed to
with the C<printf()> function.
}
=item READ this, LIST
+X<READ>
This method will be called when the handle is read from via the C<read>
or C<sysread> functions.
}
=item READLINE this
+X<READLINE>
This method will be called when the handle is read from via <HANDLE>.
The method should return undef when there is no more data.
sub READLINE { $r = shift; "READLINE called $$r times\n"; }
=item GETC this
+X<GETC>
This method will be called when the C<getc> function is called.
sub GETC { print "Don't GETC, Get Perl"; return "a"; }
=item CLOSE this
+X<CLOSE>
This method will be called when the handle is closed via the C<close>
function.
sub CLOSE { print "CLOSE called.\n" }
=item UNTIE this
+X<UNTIE>
As with the other types of ties, this method will be called when C<untie> happens.
It may be appropriate to "auto CLOSE" when this occurs. See
L<The C<untie> Gotcha> below.
=item DESTROY this
+X<DESTROY>
As with the other types of ties, this method will be called when the
tied handle is about to be destroyed. This is useful for debugging and
print <FOO>;
=head2 UNTIE this
+X<UNTIE>
You can define for all tie types an UNTIE method that will be called
at untie(). See L<The C<untie> Gotcha> below.
=head2 The C<untie> Gotcha
+X<untie>
If you intend making use of the object returned from either tie() or
tied(), and if the tie's target class defines a destructor, there is a