<P>For functions that can be used in either a scalar or list context,
nonabortive failure is generally indicated in a scalar context by
returning the undefined value, and in a list context by returning the
null list.</P>
<P>Remember the following important rule: There is <STRONG>no rule</STRONG> that relates
the behavior of an expression in list context to its behavior in scalar
context, or vice versa. It might do two totally different things.
Each operator and function decides which sort of value it would be most
appropriate to return in scalar context. Some operators return the
length of the list that would have been returned in list context. Some
operators return the first value in the list. Some operators return the
last value in the list. Some operators return a count of successful
operations. In general, they do what you want, unless you want
consistency.</P>
<P>An 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
like <CODE>(1,2,3)</CODE> into being in scalar context, because the compiler knows
the context at compile time. It would generate the scalar comma operator
there, not the list construction version of the comma. That means it
was never a list to start with.</P>
<P>In general, functions in Perl that serve as wrappers for system calls
of the same name (like chown(2), fork(2), closedir(2), etc.) all return
true when they succeed and <A HREF="#item_undef"><CODE>undef</CODE></A> otherwise, as is usually mentioned
in the descriptions below. This is different from the C interfaces,
which return <CODE>-1</CODE> on failure. Exceptions to this rule are <A HREF="#item_wait"><CODE>wait</CODE></A>,
<A HREF="#item_waitpid"><CODE>waitpid</CODE></A>, and <A HREF="#item_syscall"><CODE>syscall</CODE></A>. System calls also set the special <CODE>$!</CODE>
variable on failure. Other functions do not, except accidentally.</P>
<P>
<H2><A NAME="perl functions by category">Perl Functions by Category</A></H2>
<P>Here are Perl's functions (including things that look like
functions, like some keywords and named operators)
arranged by category. Some functions appear in more
than one place.</P>
<DL>
<DT><STRONG><A NAME="item_Functions_for_SCALARs_or_strings">Functions for SCALARs or strings</A></STRONG><BR>
<DT><STRONG><A NAME="item_Keywords_related_to_the_control_flow_of_your_perl_">Keywords related to the control flow of your perl program</A></STRONG><BR>
A file test, where X is one of the letters listed below. This unary
operator takes one argument, either a filename or a filehandle, and
tests the associated file to see if something is true about it. If the
argument is omitted, tests <CODE>$_</CODE>, except for <CODE>-t</CODE>, which tests STDIN.
Unless otherwise documented, it returns <CODE>1</CODE> for true and <CODE>''</CODE> for false, or
the undefined value if the file doesn't exist. Despite the funny
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:
<PRE>
-r File is readable by effective uid/gid.
-w File is writable by effective uid/gid.
-x File is executable by effective uid/gid.
-o File is owned by effective uid.</PRE>
<PRE>
-R File is readable by real uid/gid.
-W File is writable by real uid/gid.
-X File is executable by real uid/gid.
-O File is owned by real uid.</PRE>
<PRE>
-e File exists.
-z File has zero size.
-s File has nonzero size (returns size).</PRE>
<PRE>
-f File is a plain file.
-d File is a directory.
-l File is a symbolic link.
-p File is a named pipe (FIFO), or Filehandle is a pipe.
-S File is a socket.
-b File is a block special file.
-c File is a character special file.
-t Filehandle is opened to a tty.</PRE>
<PRE>
-u File has setuid bit set.
-g File has setgid bit set.
-k File has sticky bit set.</PRE>
<PRE>
-T File is an ASCII text file.
-B File is a "binary" file (opposite of -T).</PRE>
<PRE>
-M Age of file in days when script started.
-A Same for access time.
-C Same for inode change time.</PRE>
<P>Example:</P>
<PRE>
while (<>) {
chop;
next unless -f $_; # ignore specials
#...
}</PRE>
<P>The interpretation of the file permission operators <CODE>-r</CODE>, <CODE>-R</CODE>,
<CODE>-w</CODE>, <CODE>-W</CODE>, <CODE>-x</CODE>, and <A HREF="#item_%2DX"><CODE>-X</CODE></A> is by default based solely on the mode
of the file and the uids and gids of the user. There may be other
reasons you can't actually read, write, or execute the file. Such
reasons may be for example network filesystem access controls, ACLs
(access control lists), read-only filesystems, and unrecognized
executable formats.</P>
<P>Also note that, for the superuser on the local filesystems, the <CODE>-r</CODE>,
<CODE>-R</CODE>, <CODE>-w</CODE>, and <CODE>-W</CODE> tests always return 1, and <CODE>-x</CODE> and <A HREF="#item_%2DX"><CODE>-X</CODE></A> return 1
if any execute bit is set in the mode. Scripts run by the superuser
may thus need to do a <A HREF="#item_stat"><CODE>stat()</CODE></A> to determine the actual mode of the file,
or temporarily set their effective uid to something else.</P>
<P>If you are using ACLs, there is a pragma called <CODE>filetest</CODE> that may
produce more accurate results than the bare <A HREF="#item_stat"><CODE>stat()</CODE></A> mode bits.
When under the <CODE>use filetest 'access'</CODE> the above-mentioned filetests
will test whether the permission can (not) be granted using the
<CODE>access()</CODE> family of system calls. Also note that the <CODE>-x</CODE> and <A HREF="#item_%2DX"><CODE>-X</CODE></A> may
under this pragma return true even if there are no execute permission
bits set (nor any extra execute permission ACLs). This strangeness is
due to the underlying system calls' definitions. Read the
documentation for the <CODE>filetest</CODE> pragma for more information.</P>
<P>Note that <CODE>-s/a/b/</CODE> does not do a negated substitution. Saying
<A HREF="#item_exp"><CODE>-exp($foo)</CODE></A> still works as expected, however--only single letters
following a minus are interpreted as file tests.</P>
<P>The <CODE>-T</CODE> and <CODE>-B</CODE> switches work as follows. The first block or so of the
file is examined for odd characters such as strange control codes or
characters with the high bit set. If too many strange characters (>30%)
are found, it's a <CODE>-B</CODE> file, otherwise it's a <CODE>-T</CODE> file. Also, any file
containing null in the first block is considered a binary file. If <CODE>-T</CODE>
or <CODE>-B</CODE> is used on a filehandle, the current stdio buffer is examined
rather than the first block. Both <CODE>-T</CODE> and <CODE>-B</CODE> return true on a null
file, or a file at EOF when testing a filehandle. Because you have to
read a file to do the <CODE>-T</CODE> test, on most occasions you want to use a <CODE>-f</CODE>
against the file first, as in <CODE>next unless -f $file && -T $file</CODE>.</P>
<P>If any of the file tests (or either the <A HREF="#item_stat"><CODE>stat</CODE></A> or <A HREF="#item_lstat"><CODE>lstat</CODE></A> operators) are given
the special filehandle consisting of a solitary underline, then the stat
structure of the previous file test (or stat operator) is used, saving
a system call. (This doesn't work with <CODE>-t</CODE>, and you need to remember
that <A HREF="#item_lstat"><CODE>lstat()</CODE></A> and <CODE>-l</CODE> will leave values in the stat structure for the
Accepts an incoming socket connect, just as the <A HREF="#item_accept"><CODE>accept(2)</CODE></A> system call
does. Returns the packed address if it succeeded, false otherwise.
See the example in <A HREF="../../lib/Pod/perlipc.html#sockets: client/server communication">Sockets: Client/Server Communication in the perlipc manpage</A>.
<P>On systems that support a close-on-exec flag on files, the flag will
be set for the newly opened file descriptor, as determined by the
value of $^F. See <A HREF="../../lib/Pod/perlvar.html#$^f">$^F in the perlvar manpage</A>.</P>
Arranges for FILEHANDLE to be read or written in ``binary'' or ``text'' mode
on systems where the run-time libraries distinguish between binary and
text files. If FILEHANDLE is an expression, the value is taken as the
name of the filehandle. DISCIPLINE can be either of <CODE>":raw"</CODE> for
binary mode or <CODE>":crlf"</CODE> for ``text'' mode. If the DISCIPLINE is
omitted, it defaults to <CODE>":raw"</CODE>.
<P><A HREF="#item_binmode"><CODE>binmode()</CODE></A> should be called after <A HREF="#item_open"><CODE>open()</CODE></A> but before any I/O is done on
the filehandle.</P>
<P>On many systems <A HREF="#item_binmode"><CODE>binmode()</CODE></A> currently has no effect, but in future, it
will be extended to support user-defined input and output disciplines.
On some systems <A HREF="#item_binmode"><CODE>binmode()</CODE></A> is necessary when you're not working with a
text file. For the sake of portability it is a good idea to always use
it when appropriate, and to never use it when it isn't appropriate.</P>
<P>In other words: Regardless of platform, use <A HREF="#item_binmode"><CODE>binmode()</CODE></A> on binary
files, and do not use <A HREF="#item_binmode"><CODE>binmode()</CODE></A> on text files.</P>
<P>The <A HREF="#item_open"><CODE>open</CODE></A> pragma can be used to establish default disciplines.
See <A HREF="../../lib/open.html">the open manpage</A>.</P>
<P>The operating system, device drivers, C libraries, and Perl run-time
system all work together to let the programmer treat a single
character (<CODE>\n</CODE>) as the line terminator, irrespective of the external
representation. On many operating systems, the native text file
representation matches the internal representation, but on some
platforms the external representation of <CODE>\n</CODE> is made up of more than
one character.</P>
<P>Mac OS and all variants of Unix use a single character to end each line
in the external representation of text (even though that single
character is not necessarily the same across these platforms).
Consequently <A HREF="#item_binmode"><CODE>binmode()</CODE></A> has no effect on these operating systems. In
other systems like VMS, MS-DOS and the various flavors of MS-Windows
your program sees a <CODE>\n</CODE> as a simple <CODE>\cJ</CODE>, but what's stored in text
files are the two characters <CODE>\cM\cJ</CODE>. That means that, if you don't
use <A HREF="#item_binmode"><CODE>binmode()</CODE></A> on these systems, <CODE>\cM\cJ</CODE> sequences on disk will be
converted to <CODE>\n</CODE> on input, and any <CODE>\n</CODE> in your program will be
converted back to <CODE>\cM\cJ</CODE> on output. This is what you want for text
files, but it can be disastrous for binary files.</P>
<P>Another consequence of using <A HREF="#item_binmode"><CODE>binmode()</CODE></A> (on some systems) is that
special end-of-file markers will be seen as part of the data stream.
For systems from the Microsoft family this means that if your binary
data contains <CODE>\cZ</CODE>, the I/O subsystem will ragard it as the end of
the file, unless you use binmode().</P>
<P><A HREF="#item_binmode"><CODE>binmode()</CODE></A> is not only important for <A HREF="#item_readline"><CODE>readline()</CODE></A> and <A HREF="#item_print"><CODE>print()</CODE></A> operations,
but also when using read(), seek(), sysread(), <A HREF="#item_syswrite"><CODE>syswrite()</CODE></A> and <A HREF="#item_tell"><CODE>tell()</CODE></A>
(see <A HREF="../../lib/Pod/perlport.html">the perlport manpage</A> for more details). See the <CODE>$/</CODE> and <CODE>$\</CODE> variables
in <A HREF="../../lib/Pod/perlvar.html">the perlvar manpage</A> for how to manually set your input and output
This function tells the thingy referenced by REF that it is now an object
in the CLASSNAME package. If CLASSNAME is omitted, the current package
is used. Because a <A HREF="#item_bless"><CODE>bless</CODE></A> is often the last thing in a constructor,
it returns the reference for convenience. Always use the two-argument
version if the function doing the blessing might be inherited by a
derived class. See <A HREF="../../lib/Pod/perltoot.html">the perltoot manpage</A> and <A HREF="../../lib/Pod/perlobj.html">the perlobj manpage</A> for more about the blessing
(and blessings) of objects.
<P>Consider always blessing objects in CLASSNAMEs that are mixed case.
Namespaces with all lowercase names are considered reserved for
Perl pragmata. Builtin types have all uppercase names, so to prevent
confusion, you may wish to avoid such package names as well. Make sure
that CLASSNAME is a true value.</P>
<P>See <A HREF="../../lib/Pod/perlmod.html#perl modules">Perl Modules in the perlmod manpage</A>.</P>
<P>Here $subroutine may be <CODE>(eval)</CODE> if the frame is not a subroutine
call, but an <A HREF="#item_eval"><CODE>eval</CODE></A>. In such a case additional elements $evaltext and
<CODE>$is_require</CODE> are set: <CODE>$is_require</CODE> is true if the frame is created by a
<A HREF="#item_require"><CODE>require</CODE></A> or <A HREF="#item_use"><CODE>use</CODE></A> statement, $evaltext contains the text of the
<A HREF="#item_eval"><CODE>eval EXPR</CODE></A> statement. In particular, for a <A HREF="#item_eval"><CODE>eval BLOCK</CODE></A> statement,
$filename is <CODE>(eval)</CODE>, but $evaltext is undefined. (Note also that
each <A HREF="#item_use"><CODE>use</CODE></A> statement creates a <A HREF="#item_require"><CODE>require</CODE></A> frame inside an <A HREF="#item_eval"><CODE>eval EXPR</CODE></A>)
frame. <CODE>$hints</CODE> and <CODE>$bitmask</CODE> contain pragmatic hints that the caller
was compiled with. The <CODE>$hints</CODE> and <CODE>$bitmask</CODE> values are subject to
change between versions of Perl, and are not meant for external use.</P>
<P>Furthermore, when called from within the DB package, caller returns more
detailed information: it sets the list variable <CODE>@DB::args</CODE> to be the
arguments with which the subroutine was invoked.</P>
<P>Be aware that the optimizer might have optimized call frames away before
<A HREF="#item_caller"><CODE>caller</CODE></A> had a chance to get the information. That means that <A HREF="#item_caller"><CODE>caller(N)</CODE></A>
might not return information about the call frame you expect it do, for
<CODE>N > 1</CODE>. In particular, <CODE>@DB::args</CODE> might have information from the
previous time <A HREF="#item_caller"><CODE>caller</CODE></A> was called.</P>
This safer version of <A HREF="#chop">chop</A> removes any trailing string
that corresponds to the current value of <CODE>$/</CODE> (also known as
$INPUT_RECORD_SEPARATOR in the <CODE>English</CODE> module). It returns the total
number of characters removed from all its arguments. It's often used to
remove the newline from the end of an input record when you're worried
that the final record may be missing its newline. When in paragraph
mode (<CODE>$/ = ""</CODE>), it removes all trailing newlines from the string.
When in slurp mode (<CODE>$/ = undef</CODE>) or fixed-length record mode (<CODE>$/</CODE> is
a reference to an integer or the like, see <A HREF="../../lib/Pod/perlvar.html">the perlvar manpage</A>) <A HREF="#item_chomp"><CODE>chomp()</CODE></A> won't
remove anything.
If VARIABLE is omitted, it chomps <CODE>$_</CODE>. Example:
<PRE>
while (<>) {
chomp; # avoid \n on last field
@array = split(/:/);
# ...
}</PRE>
<P>You can actually chomp anything that's an lvalue, including an assignment:</P>
<PRE>
chomp($cwd = `pwd`);
chomp($answer = <STDIN>);</PRE>
<P>If you chomp a list, each element is chomped, and the total number of
Actually a flow control statement rather than a function. If there is a
<A HREF="#item_continue"><CODE>continue</CODE></A> BLOCK attached to a BLOCK (typically in a <CODE>while</CODE> or
<CODE>foreach</CODE>), it is always executed just before the conditional is about to
be evaluated again, just like the third part of a <CODE>for</CODE> loop in C. Thus
it can be used to increment a loop variable, even when the loop has been
continued via the <A HREF="#item_next"><CODE>next</CODE></A> statement (which is similar to the C <A HREF="#item_continue"><CODE>continue</CODE></A>
statement).
<P><A HREF="#item_last"><CODE>last</CODE></A>, <A HREF="#item_next"><CODE>next</CODE></A>, or <A HREF="#item_redo"><CODE>redo</CODE></A> may appear within a <A HREF="#item_continue"><CODE>continue</CODE></A>
block. <A HREF="#item_last"><CODE>last</CODE></A> and <A HREF="#item_redo"><CODE>redo</CODE></A> will behave as if they had been executed within
the main block. So will <A HREF="#item_next"><CODE>next</CODE></A>, but since it will execute a <A HREF="#item_continue"><CODE>continue</CODE></A>
block, it may be more entertaining.</P>
<PRE>
while (EXPR) {
### redo always comes here
do_something;
} continue {
### next always comes here
do_something_else;
# then back the top to re-check EXPR
}
### last always comes here</PRE>
<P>Omitting the <A HREF="#item_continue"><CODE>continue</CODE></A> section is semantically equivalent to using an
empty one, logically enough. In that case, <A HREF="#item_next"><CODE>next</CODE></A> goes directly back
to check the condition at the top of the loop.</P>
Outside an <A HREF="#item_eval"><CODE>eval</CODE></A>, prints the value of LIST to <CODE>STDERR</CODE> and
exits with the current value of <CODE>$!</CODE> (errno). If <CODE>$!</CODE> is <CODE>0</CODE>,
exits with the value of <CODE>($? >> 8)</CODE> (backtick `command`
status). If <CODE>($? >> 8)</CODE> is <CODE>0</CODE>, exits with <CODE>255</CODE>. Inside
an <A HREF="#item_eval"><CODE>eval(),</CODE></A> the error message is stuffed into <CODE>$@</CODE> and the
<A HREF="#item_eval"><CODE>eval</CODE></A> is terminated with the undefined value. This makes
<A HREF="#item_die"><CODE>die</CODE></A> the way to raise an exception.
<P>Equivalent examples:</P>
<PRE>
die "Can't cd to spool: $!\n" unless chdir '/usr/spool/news';
chdir '/usr/spool/news' or die "Can't cd to spool: $!\n"</PRE>
<P>If the value of EXPR does not end in a newline, the current script line
number and input line number (if any) are also printed, and a newline
is supplied. Note that the ``input line number'' (also known as ``chunk'')
is subject to whatever notion of ``line'' happens to be currently in
effect, and is also available as the special variable <CODE>$.</CODE>.
See <A HREF="../../lib/Pod/perlvar.html#$/">$/ in the perlvar manpage</A> and <A HREF="../../lib/Pod/perlvar.html#$.">$. in the perlvar manpage</A>.</P>
<P>Hint: sometimes appending <CODE>", stopped"</CODE> to your message
will cause it to make better sense when the string <CODE>"at foo line 123"</CODE> is
appended. Suppose you are running script ``canasta''.</P>
<PRE>
die "/etc/games is no good";
die "/etc/games is no good, stopped";</PRE>
<P>produce, respectively</P>
<PRE>
/etc/games is no good at canasta line 123.
/etc/games is no good, stopped at canasta line 123.</PRE>
<P>See also exit(), warn(), and the Carp module.</P>
<P>If LIST is empty and <CODE>$@</CODE> already contains a value (typically from a
previous eval) that value is reused after appending <CODE>"\t...propagated"</CODE>.
This is useful for propagating exceptions:</P>
<PRE>
eval { ... };
die unless $@ =~ /Expected exception/;</PRE>
<P>If <CODE>$@</CODE> is empty then the string <CODE>"Died"</CODE> is used.</P>
<P><A HREF="#item_die"><CODE>die()</CODE></A> can also be called with a reference argument. If this happens to be
trapped within an eval(), $@ contains the reference. This behavior permits
a more elaborate exception handling implementation using objects that
maintain arbitary state about the nature of the exception. Such a scheme
is sometimes preferable to matching particular string values of $@ using
Not really a function. Returns the value of the last command in the
sequence of commands indicated by BLOCK. When modified by a loop
modifier, executes the BLOCK once before testing the loop condition.
(On other statements the loop modifiers test the conditional first.)
<P><A HREF="#item_do"><CODE>do BLOCK</CODE></A> does <EM>not</EM> count as a loop, so the loop control statements
<A HREF="#item_next"><CODE>next</CODE></A>, <A HREF="#item_last"><CODE>last</CODE></A>, or <A HREF="#item_redo"><CODE>redo</CODE></A> cannot be used to leave or restart the block.
See <A HREF="../../lib/Pod/perlsyn.html">the perlsyn manpage</A> for alternative strategies.</P>
A deprecated form of subroutine call. See <A HREF="../../lib/Pod/perlsub.html">the perlsub manpage</A>.
<P></P>
<DT><STRONG>do EXPR</STRONG><BR>
<DD>
Uses the value of EXPR as a filename and executes the contents of the
file as a Perl script. Its primary use is to include subroutines
from a Perl subroutine library.
<PRE>
do 'stat.pl';</PRE>
<P>is just like</P>
<PRE>
scalar eval `cat stat.pl`;</PRE>
<P>except that it's more efficient and concise, keeps track of the current
filename for error messages, searches the @INC libraries, and updates
<CODE>%INC</CODE> if the file is found. See <A HREF="../../lib/Pod/perlvar.html#predefined names">Predefined Names in the perlvar manpage</A> for these
variables. It also differs in that code evaluated with <A HREF="#item_do"><CODE>do FILENAME</CODE></A>
cannot see lexicals in the enclosing scope; <A HREF="#item_eval"><CODE>eval STRING</CODE></A> does. It's the
same, however, in that it does reparse the file every time you call it,
so you probably don't want to do this inside a loop.</P>
<P>If <A HREF="#item_do"><CODE>do</CODE></A> cannot read the file, it returns undef and sets <CODE>$!</CODE> to the
error. If <A HREF="#item_do"><CODE>do</CODE></A> can read the file but cannot compile it, it
returns undef and sets an error message in <CODE>$@</CODE>. If the file is
successfully compiled, <A HREF="#item_do"><CODE>do</CODE></A> returns the value of the last expression
evaluated.</P>
<P>Note that inclusion of library modules is better done with the
<A HREF="#item_use"><CODE>use</CODE></A> and <A HREF="#item_require"><CODE>require</CODE></A> operators, which also do automatic error checking
and raise an exception if there's a problem.</P>
<P>You might like to use <A HREF="#item_do"><CODE>do</CODE></A> to read in a program configuration
file. Manual error checking can be done this way:</P>
<PRE>
# read in config files: system first, then user
for $file ("/share/prog/defaults.rc",
"$ENV{HOME}/.someprogrc")
{
unless ($return = do $file) {
warn "couldn't parse $file: $@" if $@;
warn "couldn't do $file: $!" unless defined $return;
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
it. When called in scalar context, returns the key for only the ``next''
element in the hash.
<P>Entries are returned in an apparently random order. The actual random
order is subject to change in future versions of perl, but it is guaranteed
to be in the same order as either the <A HREF="#item_keys"><CODE>keys</CODE></A> or <A HREF="#item_values"><CODE>values</CODE></A> function
would produce on the same (unmodified) hash.</P>
<P>When the hash is entirely read, a null array is returned in list context
(which when assigned produces a false (<CODE>0</CODE>) value), and <A HREF="#item_undef"><CODE>undef</CODE></A> in
scalar context. The next call to <A HREF="#item_each"><CODE>each</CODE></A> after that will start iterating
again. There is a single iterator for each hash, shared by all <A HREF="#item_each"><CODE>each</CODE></A>,
<A HREF="#item_keys"><CODE>keys</CODE></A>, and <A HREF="#item_values"><CODE>values</CODE></A> function calls in the program; it can be reset by
reading all the elements from the hash, or by evaluating <A HREF="#item_keys"><CODE>keys HASH</CODE></A> or
<A HREF="#item_values"><CODE>values HASH</CODE></A>. If you add or delete elements of a hash while you're
iterating over it, you may get entries skipped or duplicated, so don't.</P>
<P>The following prints out your environment like the <CODE>printenv(1)</CODE> program,
only in a different order:</P>
<PRE>
while (($key,$value) = each %ENV) {
print "$key=$value\n";
}</PRE>
<P>See also <A HREF="#item_keys"><CODE>keys</CODE></A>, <A HREF="#item_values"><CODE>values</CODE></A> and <A HREF="#item_sort"><CODE>sort</CODE></A>.</P>
In the first form, the return value of EXPR is parsed and executed as if it
were a little Perl program. The value of the expression (which is itself
determined within scalar context) is first parsed, and if there weren't any
errors, executed in the context of the current Perl program, so that any
variable settings or subroutine and format definitions remain afterwards.
Note that the value is parsed every time the eval executes. If EXPR is
omitted, evaluates <CODE>$_</CODE>. This form is typically used to delay parsing
and subsequent execution of the text of EXPR until run time.
<P>In the second form, the code within the BLOCK is parsed only once--at the
same time the code surrounding the eval itself was parsed--and executed
within the context of the current Perl program. This form is typically
used to trap exceptions more efficiently than the first (see below), while
also providing the benefit of checking the code within BLOCK at compile
time.</P>
<P>The final semicolon, if any, may be omitted from the value of EXPR or within
the BLOCK.</P>
<P>In both forms, the value returned is the value of the last expression
evaluated inside the mini-program; a return statement may be also used, just
as with subroutines. The expression providing the return value is evaluated
in void, scalar, or list context, depending on the context of the eval itself.
See <A HREF="#wantarray">wantarray</A> for more on how the evaluation context can be determined.</P>
<P>If there is a syntax error or runtime error, or a <A HREF="#item_die"><CODE>die</CODE></A> statement is
executed, an undefined value is returned by <A HREF="#item_eval"><CODE>eval</CODE></A>, and <CODE>$@</CODE> is set to the
error message. If there was no error, <CODE>$@</CODE> is guaranteed to be a null
string. Beware that using <A HREF="#item_eval"><CODE>eval</CODE></A> neither silences perl from printing
warnings to STDERR, nor does it stuff the text of warning messages into <CODE>$@</CODE>.
To do either of those, you have to use the <CODE>$SIG{__WARN__}</CODE> facility. See
<A HREF="#warn">warn</A> and <A HREF="../../lib/Pod/perlvar.html">the perlvar manpage</A>.</P>
<P>Note that, because <A HREF="#item_eval"><CODE>eval</CODE></A> traps otherwise-fatal errors, it is useful for
determining whether a particular feature (such as <A HREF="#item_socket"><CODE>socket</CODE></A> or <A HREF="#item_symlink"><CODE>symlink</CODE></A>)
is implemented. It is also Perl's exception trapping mechanism, where
the die operator is used to raise exceptions.</P>
<P>If the code to be executed doesn't vary, you may use the eval-BLOCK
form to trap run-time errors without incurring the penalty of
recompiling each time. The error, if any, is still returned in <CODE>$@</CODE>.
Examples:</P>
<PRE>
# make divide-by-zero nonfatal
eval { $answer = $a / $b; }; warn $@ if $@;</PRE>
<PRE>
# same thing, but less efficient
eval '$answer = $a / $b'; warn $@ if $@;</PRE>
<PRE>
# a compile-time error
eval { $answer = }; # WRONG</PRE>
<PRE>
# a run-time error
eval '$answer ='; # sets $@</PRE>
<P>Due to the current arguably broken state of <CODE>__DIE__</CODE> hooks, when using
the <A HREF="#item_eval"><CODE>eval{}</CODE></A> form as an exception trap in libraries, you may wish not
to trigger any <CODE>__DIE__</CODE> hooks that user code may have installed.
You can use the <CODE>local $SIG{__DIE__}</CODE> construct for this purpose,
as shown in this example:</P>
<PRE>
# a very private exception trap for divide-by-zero
eval { local $SIG{'__DIE__'}; $answer = $a / $b; };
warn $@ if $@;</PRE>
<P>This is especially significant, given that <CODE>__DIE__</CODE> hooks can call
<A HREF="#item_die"><CODE>die</CODE></A> again, which has the effect of changing their error messages:</P>
<PRE>
# __DIE__ hooks may modify error messages
{
local $SIG{'__DIE__'} =
sub { (my $x = $_[0]) =~ s/foo/bar/g; die $x };
eval { die "foo lives here" };
print $@ if $@; # prints "bar lives here"
}</PRE>
<P>Because this promotes action at a distance, this counterintuitive behavior
may be fixed in a future release.</P>
<P>With an <A HREF="#item_eval"><CODE>eval</CODE></A>, you should be especially careful to remember what's
being looked at when:</P>
<PRE>
eval $x; # CASE 1
eval "$x"; # CASE 2</PRE>
<PRE>
eval '$x'; # CASE 3
eval { $x }; # CASE 4</PRE>
<PRE>
eval "\$$x++"; # CASE 5
$$x++; # CASE 6</PRE>
<P>Cases 1 and 2 above behave identically: they run the code contained in
the variable $x. (Although case 2 has misleading double quotes making
the reader wonder what else might be happening (nothing is).) Cases 3
and 4 likewise behave in the same way: they run the code <CODE>'$x'</CODE>, which
does nothing but return the value of $x. (Case 4 is preferred for
purely visual reasons, but it also has the advantage of compiling at
compile-time instead of at run-time.) Case 5 is a place where
normally you <EM>would</EM> like to use double quotes, except that in this
particular situation, you can just use symbolic references instead, as
in case 6.</P>
<P><A HREF="#item_eval"><CODE>eval BLOCK</CODE></A> does <EM>not</EM> count as a loop, so the loop control statements
<A HREF="#item_next"><CODE>next</CODE></A>, <A HREF="#item_last"><CODE>last</CODE></A>, or <A HREF="#item_redo"><CODE>redo</CODE></A> cannot be used to leave or restart the block.</P>
Given an expression that specifies a hash element or array element,
returns true if the specified element in the hash or array has ever
been initialized, even if the corresponding value is undefined. The
element is not autovivified if it doesn't exist.
<PRE>
print "Exists\n" if exists $hash{$key};
print "Defined\n" if defined $hash{$key};
print "True\n" if $hash{$key};</PRE>
<PRE>
print "Exists\n" if exists $array[$index];
print "Defined\n" if defined $array[$index];
print "True\n" if $array[$index];</PRE>
<P>A hash or array element can be true only if it's defined, and defined if
it exists, but the reverse doesn't necessarily hold true.</P>
<P>Given an expression that specifies the name of a subroutine,
returns true if the specified subroutine has ever been declared, even
if it is undefined. Mentioning a subroutine name for exists or defined
does not count as declaring it.</P>
<PRE>
print "Exists\n" if exists &subroutine;
print "Defined\n" if defined &subroutine;</PRE>
<P>Note that the EXPR can be arbitrarily complicated as long as the final
operation is a hash or array key lookup or subroutine name:</P>
<PRE>
if (exists $ref->{A}->{B}->{$key}) { }
if (exists $hash{A}{B}{$key}) { }</PRE>
<PRE>
if (exists $ref->{A}->{B}->[$ix]) { }
if (exists $hash{A}{B}[$ix]) { }</PRE>
<PRE>
if (exists &{$ref->{A}{B}{$key}}) { }</PRE>
<P>Although the deepest nested array or hash will not spring into existence
just because its existence was tested, any intervening ones will.
Thus <CODE>$ref->{"A"}</CODE> and <CODE>$ref->{"A"}->{"B"}</CODE> will spring
into existence due to the existence test for the $key element above.
This happens anywhere the arrow operator is used, including even:</P>
<PRE>
undef $ref;
if (exists $ref->{"Some key"}) { }
print $ref; # prints HASH(0x80d3d5c)</PRE>
<P>This surprising autovivification in what does not at first--or even
second--glance appear to be an lvalue context may be fixed in a future
release.</P>
<P>See <A HREF="../../lib/Pod/perlref.html#pseudohashes: using an array as a hash">Pseudo-hashes: Using an array as a hash in the perlref manpage</A> for specifics
on how <A HREF="#item_exists"><CODE>exists()</CODE></A> acts when used on a pseudo-hash.</P>
<P>Use of a subroutine call, rather than a subroutine name, as an argument
to <A HREF="#item_exists"><CODE>exists()</CODE></A> is an error.</P>
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
machine that doesn't implement flock(2), <A HREF="#item_fcntl"><CODE>fcntl(2)</CODE></A> locking, or lockf(3).
<A HREF="#item_flock"><CODE>flock</CODE></A> is Perl's portable file locking interface, although it locks
only entire files, not records.
<P>Two potentially non-obvious but traditional <A HREF="#item_flock"><CODE>flock</CODE></A> semantics are
that it waits indefinitely until the lock is granted, and that its locks
<STRONG>merely advisory</STRONG>. Such discretionary locks are more flexible, but offer
fewer guarantees. This means that files locked with <A HREF="#item_flock"><CODE>flock</CODE></A> may be
modified by programs that do not also use <A HREF="#item_flock"><CODE>flock</CODE></A>. See <A HREF="../../lib/Pod/perlport.html">the perlport manpage</A>,
your port's specific documentation, or your system-specific local manpages
for details. It's best to assume traditional behavior if you're writing
portable programs. (But if you're not, you should as always feel perfectly
free to write for your own system's idiosyncrasies (sometimes called
``features''). Slavish adherence to portability concerns shouldn't get
in the way of your getting your job done.)</P>
<P>OPERATION is one of LOCK_SH, LOCK_EX, or LOCK_UN, possibly combined with
LOCK_NB. These constants are traditionally valued 1, 2, 8 and 4, but
you can use the symbolic names if you import them from the Fcntl module,
either individually, or as a group using the ':flock' tag. LOCK_SH
requests a shared lock, LOCK_EX requests an exclusive lock, and LOCK_UN
releases a previously requested lock. If LOCK_NB is bitwise-or'ed with
LOCK_SH or LOCK_EX then <A HREF="#item_flock"><CODE>flock</CODE></A> will return immediately rather than blocking
waiting for the lock (check the return status to see if you got it).</P>
<P>To avoid the possibility of miscoordination, Perl now flushes FILEHANDLE
before locking or unlocking it.</P>
<P>Note that the emulation built with <CODE>lockf(3)</CODE> doesn't provide shared
locks, and it requires that FILEHANDLE be open with write intent. These
are the semantics that <CODE>lockf(3)</CODE> implements. Most if not all systems
implement <CODE>lockf(3)</CODE> in terms of <A HREF="#item_fcntl"><CODE>fcntl(2)</CODE></A> locking, though, so the
differing semantics shouldn't bite too many people.</P>
<P>Note also that some versions of <A HREF="#item_flock"><CODE>flock</CODE></A> cannot lock things over the
network; you would need to use the more system-specific <A HREF="#item_fcntl"><CODE>fcntl</CODE></A> for
that. If you like you can force Perl to ignore your system's <A HREF="#item_flock"><CODE>flock(2)</CODE></A>
function, and so provide its own fcntl(2)-based emulation, by passing
the switch <CODE>-Ud_flock</CODE> to the <EM>Configure</EM> program when you configure
perl.</P>
<P>Here's a mailbox appender for BSD systems.</P>
<PRE>
use Fcntl ':flock'; # import LOCK_* constants</PRE>
<PRE>
sub lock {
flock(MBOX,LOCK_EX);
# and, in case someone appended
# while we were waiting...
seek(MBOX, 0, 2);
}</PRE>
<PRE>
sub unlock {
flock(MBOX,LOCK_UN);
}</PRE>
<PRE>
open(MBOX, ">>/usr/spool/mail/$ENV{'USER'}")
or die "Can't open mailbox: $!";</PRE>
<PRE>
lock();
print MBOX $msg,"\n\n";
unlock();</PRE>
<P>On systems that support a real flock(), locks are inherited across <A HREF="#item_fork"><CODE>fork()</CODE></A>
calls, whereas those that must resort to the more capricious <A HREF="#item_fcntl"><CODE>fcntl()</CODE></A>
function lose the locks, making it harder to write servers.</P>
<P>See also <A HREF="../../lib/DB_File.html">the DB_File manpage</A> for other <A HREF="#item_flock"><CODE>flock()</CODE></A> examples.</P>
This is an internal function used by <A HREF="#item_format"><CODE>format</CODE></A>s, though you may call it,
too. It formats (see <A HREF="../../lib/Pod/perlform.html">the perlform manpage</A>) a list of values according to the
contents of PICTURE, placing the output into the format output
accumulator, <CODE>$^A</CODE> (or <CODE>$ACCUMULATOR</CODE> in English).
Eventually, when a <A HREF="#item_write"><CODE>write</CODE></A> is done, the contents of
<CODE>$^A</CODE> are written to some filehandle, but you could also read <CODE>$^A</CODE>
yourself and then set <CODE>$^A</CODE> back to <CODE>""</CODE>. Note that a format typically
does one <A HREF="#item_formline"><CODE>formline</CODE></A> per line of form, but the <A HREF="#item_formline"><CODE>formline</CODE></A> function itself
doesn't care how many newlines are embedded in the PICTURE. This means
that the <CODE>~</CODE> and <CODE>~~</CODE> tokens will treat the entire PICTURE as a single line.
You may therefore need to use multiple formlines to implement a single
record format, just like the format compiler.
<P>Be careful if you put double quotes around the picture, because an <CODE>@</CODE>
character may be taken to mean the beginning of an array name.
<A HREF="#item_formline"><CODE>formline</CODE></A> always returns true. See <A HREF="../../lib/Pod/perlform.html">the perlform manpage</A> for other examples.</P>
Converts a time as returned by the time function to a 8-element list
with the time localized for the standard Greenwich time zone.
Typically used as follows:
<PRE>
# 0 1 2 3 4 5 6 7
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =
gmtime(time);</PRE>
<P>All list elements are numeric, and come straight out of the C `struct
tm'. $sec, $min, and $hour are the seconds, minutes, and hours of the
specified time. $mday is the day of the month, and $mon is the month
itself, in the range <CODE>0..11</CODE> with 0 indicating January and 11
indicating December. $year is the number of years since 1900. That
is, $year is <CODE>123</CODE> in year 2023. $wday is the day of the week, with
0 indicating Sunday and 3 indicating Wednesday. $yday is the day of
the year, in the range <CODE>1..365</CODE> (or <CODE>1..366</CODE> in leap years.)</P>
<P>Note that the $year element is <EM>not</EM> simply the last two digits of
the year. If you assume it is, then you create non-Y2K-compliant
programs--and you wouldn't want to do that, would you?</P>
<P>The proper way to get a complete 4-digit year is simply:</P>
<PRE>
$year += 1900;</PRE>
<P>And to get the last two digits of the year (e.g., '01' in 2001) do:</P>
<PRE>
$year = sprintf("%02d", $year % 100);</PRE>
<P>If EXPR is omitted, <A HREF="#item_gmtime"><CODE>gmtime()</CODE></A> uses the current time (<A HREF="#item_gmtime"><CODE>gmtime(time)</CODE></A>).</P>
<P>In scalar context, <A HREF="#item_gmtime"><CODE>gmtime()</CODE></A> returns the <CODE>ctime(3)</CODE> value:</P>
<PRE>
$now_string = gmtime; # e.g., "Thu Oct 13 04:54:34 1994"</PRE>
<P>Also see the <CODE>timegm</CODE> function provided by the <CODE>Time::Local</CODE> module,
and the <CODE>strftime(3)</CODE> function available via the POSIX module.</P>
<P>This scalar value is <STRONG>not</STRONG> locale dependent (see <A HREF="../../lib/Pod/perllocale.html">the perllocale manpage</A>), but
is instead a Perl builtin. Also see the <CODE>Time::Local</CODE> module, and the
<CODE>strftime(3)</CODE> and <CODE>mktime(3)</CODE> functions available via the POSIX module. To
get somewhat similar but locale dependent date strings, set up your
locale environment variables appropriately (please see <A HREF="../../lib/Pod/perllocale.html">the perllocale manpage</A>)
There is no builtin <A HREF="#item_import"><CODE>import</CODE></A> function. It is just an ordinary
method (subroutine) defined (or inherited) by modules that wish to export
names to another module. The <A HREF="#item_use"><CODE>use</CODE></A> function calls the <A HREF="#item_import"><CODE>import</CODE></A> method
for the package used. See also <A HREF="#use()">use()</A>, <A HREF="../../lib/Pod/perlmod.html">the perlmod manpage</A>, and <A HREF="../../lib/Exporter.html">the Exporter manpage</A>.
Returns the integer portion of EXPR. If EXPR is omitted, uses <CODE>$_</CODE>.
You should not use this function for rounding: one because it truncates
towards <CODE>0</CODE>, and two because machine representations of floating point
numbers can sometimes produce counterintuitive results. For example,
<A HREF="#item_int"><CODE>int(-6.725/0.025)</CODE></A> produces -268 rather than the correct -269; that's
because it's really more like -268.99999999999994315658 instead. Usually,
the <A HREF="#item_sprintf"><CODE>sprintf</CODE></A>, <A HREF="#item_printf"><CODE>printf</CODE></A>, or the <CODE>POSIX::floor</CODE> and <CODE>POSIX::ceil</CODE>
Implements the <A HREF="#item_ioctl"><CODE>ioctl(2)</CODE></A> function. You'll probably first have to say
<PRE>
require "ioctl.ph"; # probably in /usr/local/lib/perl/ioctl.ph</PRE>
<P>to get the correct function definitions. If <EM>ioctl.ph</EM> doesn't
exist or doesn't have the correct definitions you'll have to roll your
own, based on your C header files such as <EM><sys/ioctl.h</EM> >>.
(There is a Perl script called <STRONG>h2ph</STRONG> that comes with the Perl kit that
may help you in this, but it's nontrivial.) SCALAR will be read and/or
written depending on the FUNCTION--a pointer to the string value of SCALAR
will be passed as the third argument of the actual <A HREF="#item_ioctl"><CODE>ioctl</CODE></A> call. (If SCALAR
has no string value but does have a numeric value, that value will be
passed rather than a pointer to the string value. To guarantee this to be
true, add a <CODE>0</CODE> to the scalar before using it.) The <A HREF="#item_pack"><CODE>pack</CODE></A> and <A HREF="#item_unpack"><CODE>unpack</CODE></A>
functions may be needed to manipulate the values of structures used by
<A HREF="#item_ioctl"><CODE>ioctl</CODE></A>.</P>
<P>The return value of <A HREF="#item_ioctl"><CODE>ioctl</CODE></A> (and <A HREF="#item_fcntl"><CODE>fcntl</CODE></A>) is as follows:</P>
<PRE>
if OS returns: then Perl returns:
-1 undefined value
0 string "0 but true"
anything else that number</PRE>
<P>Thus Perl returns true on success and false on failure, yet you can
still easily determine the actual value returned by the operating
system:</P>
<PRE>
$retval = ioctl(...) || -1;
printf "System returned %d\n", $retval;</PRE>
<P>The special string ``<CODE>0</CODE> but true'' is exempt from <STRONG>-w</STRONG> complaints
about improper numeric conversions.</P>
<P>Here's an example of setting a filehandle named <CODE>REMOTE</CODE> to be
non-blocking at the system level. You'll have to negotiate <CODE>$|</CODE>
on your own, though.</P>
<PRE>
use Fcntl qw(F_GETFL F_SETFL O_NONBLOCK);</PRE>
<PRE>
$flags = fcntl(REMOTE, F_GETFL, 0)
or die "Can't get flags for the socket: $!\n";</PRE>
<P>As an lvalue <A HREF="#item_keys"><CODE>keys</CODE></A> allows you to increase the number of hash buckets
allocated for the given hash. This can gain you a measure of efficiency if
you know the hash is going to get big. (This is similar to pre-extending
an array by assigning a larger number to $#array.) If you say</P>
<PRE>
keys %hash = 200;</PRE>
<P>then <CODE>%hash</CODE> will have at least 200 buckets allocated for it--256 of them,
in fact, since it rounds up to the next power of two. These
buckets will be retained even if you do <CODE>%hash = ()</CODE>, use <CODE>undef
%hash</CODE> if you want to free the storage while <CODE>%hash</CODE> is still in scope.
You can't shrink the number of buckets allocated for the hash using
<A HREF="#item_keys"><CODE>keys</CODE></A> in this way (but you needn't worry about doing this by accident,
as trying has no effect).</P>
<P>See also <A HREF="#item_each"><CODE>each</CODE></A>, <A HREF="#item_values"><CODE>values</CODE></A> and <A HREF="#item_sort"><CODE>sort</CODE></A>.</P>
The <A HREF="#item_last"><CODE>last</CODE></A> command is like the <CODE>break</CODE> statement in C (as used in
loops); it immediately exits the loop in question. If the LABEL is
omitted, the command refers to the innermost enclosing loop. The
<A HREF="#item_continue"><CODE>continue</CODE></A> block, if any, is not executed:
<PRE>
LINE: while (<STDIN>) {
last LINE if /^$/; # exit when done with header
#...
}</PRE>
<P><A HREF="#item_last"><CODE>last</CODE></A> cannot be used to exit a block which returns a value such as
<A HREF="#item_eval"><CODE>eval {}</CODE></A>, <A HREF="#item_sub"><CODE>sub {}</CODE></A> or <A HREF="#item_do"><CODE>do {}</CODE></A>, and should not be used to exit
a <A HREF="#item_grep"><CODE>grep()</CODE></A> or <A HREF="#item_map"><CODE>map()</CODE></A> operation.</P>
<P>Note that a block by itself is semantically identical to a loop
that executes once. Thus <A HREF="#item_last"><CODE>last</CODE></A> can be used to effect an early
exit out of such a block.</P>
<P>See also <A HREF="#continue">continue</A> for an illustration of how <A HREF="#item_last"><CODE>last</CODE></A>, <A HREF="#item_next"><CODE>next</CODE></A>, and
Does the same thing that the listen system call does. Returns true if
it succeeded, false otherwise. See the example in <A HREF="../../lib/Pod/perlipc.html#sockets: client/server communication">Sockets: Client/Server Communication in the perlipc manpage</A>.
You really probably want to be using <A HREF="#item_my"><CODE>my</CODE></A> instead, because <A HREF="#item_local"><CODE>local</CODE></A> isn't
what most people think of as ``local''. See <A HREF="../../lib/Pod/perlsub.html#private variables via my()">Private Variables via my() in the perlsub manpage</A> for details.
<P>A local modifies the listed variables to be local to the enclosing
block, file, or eval. If more than one value is listed, the list must
be placed in parentheses. See <A HREF="../../lib/Pod/perlsub.html#temporary values via local()">Temporary Values via local() in the perlsub manpage</A>
for details, including issues with tied arrays and hashes.</P>
<P>All list elements are numeric, and come straight out of the C `struct
tm'. $sec, $min, and $hour are the seconds, minutes, and hours of the
specified time. $mday is the day of the month, and $mon is the month
itself, in the range <CODE>0..11</CODE> with 0 indicating January and 11
indicating December. $year is the number of years since 1900. That
is, $year is <CODE>123</CODE> in year 2023. $wday is the day of the week, with
0 indicating Sunday and 3 indicating Wednesday. $yday is the day of
the year, in the range <CODE>1..365</CODE> (or <CODE>1..366</CODE> in leap years.) $isdst
is true if the specified time occurs during daylight savings time,
false otherwise.</P>
<P>Note that the $year element is <EM>not</EM> simply the last two digits of
the year. If you assume it is, then you create non-Y2K-compliant
programs--and you wouldn't want to do that, would you?</P>
<P>The proper way to get a complete 4-digit year is simply:</P>
<PRE>
$year += 1900;</PRE>
<P>And to get the last two digits of the year (e.g., '01' in 2001) do:</P>
<PRE>
$year = sprintf("%02d", $year % 100);</PRE>
<P>If EXPR is omitted, <A HREF="#item_localtime"><CODE>localtime()</CODE></A> uses the current time (<A HREF="#item_localtime"><CODE>localtime(time)</CODE></A>).</P>
<P>In scalar context, <A HREF="#item_localtime"><CODE>localtime()</CODE></A> returns the <CODE>ctime(3)</CODE> value:</P>
<PRE>
$now_string = localtime; # e.g., "Thu Oct 13 04:54:34 1994"</PRE>
<P>This scalar value is <STRONG>not</STRONG> locale dependent, see <A HREF="../../lib/Pod/perllocale.html">the perllocale manpage</A>, but
instead a Perl builtin. Also see the <CODE>Time::Local</CODE> module
(to convert the second, minutes, hours, ... back to seconds since the
stroke of midnight the 1st of January 1970, the value returned by
time()), and the <CODE>strftime(3)</CODE> and <CODE>mktime(3)</CODE> functions available via the
POSIX module. To get somewhat similar but locale dependent date
strings, set up your locale environment variables appropriately
(please see <A HREF="../../lib/Pod/perllocale.html">the perllocale manpage</A>) and try for example:</P>
The <A HREF="#item_next"><CODE>next</CODE></A> command is like the <A HREF="#item_continue"><CODE>continue</CODE></A> statement in C; it starts
the next iteration of the loop:
<PRE>
LINE: while (<STDIN>) {
next LINE if /^#/; # discard comments
#...
}</PRE>
<P>Note that if there were a <A HREF="#item_continue"><CODE>continue</CODE></A> block on the above, it would get
executed even on discarded lines. If the LABEL is omitted, the command
refers to the innermost enclosing loop.</P>
<P><A HREF="#item_next"><CODE>next</CODE></A> cannot be used to exit a block which returns a value such as
<A HREF="#item_eval"><CODE>eval {}</CODE></A>, <A HREF="#item_sub"><CODE>sub {}</CODE></A> or <A HREF="#item_do"><CODE>do {}</CODE></A>, and should not be used to exit
a <A HREF="#item_grep"><CODE>grep()</CODE></A> or <A HREF="#item_map"><CODE>map()</CODE></A> operation.</P>
<P>Note that a block by itself is semantically identical to a loop
that executes once. Thus <A HREF="#item_next"><CODE>next</CODE></A> will exit such a block early.</P>
<P>See also <A HREF="#continue">continue</A> for an illustration of how <A HREF="#item_last"><CODE>last</CODE></A>, <A HREF="#item_next"><CODE>next</CODE></A>, and
Opens the file whose filename is given by EXPR, and associates it with
FILEHANDLE. If FILEHANDLE is an expression, its value is used as the
name of the real filehandle wanted. (This is considered a symbolic
reference, so <CODE>use strict 'refs'</CODE> should <EM>not</EM> be in effect.)
<P>If EXPR is omitted, the scalar
variable of the same name as the FILEHANDLE contains the filename.
(Note that lexical variables--those declared with <A HREF="#item_my"><CODE>my</CODE></A>--will not work
for this purpose; so if you're using <A HREF="#item_my"><CODE>my</CODE></A>, specify EXPR in your call
to open.) See <A HREF="../../lib/Pod/perlopentut.html">the perlopentut manpage</A> for a kinder, gentler explanation of opening
files.</P>
<P>If MODE is <CODE>'<'</CODE> or nothing, the file is opened for input.
If MODE is <CODE>'>'</CODE>, the file is truncated and opened for
output, being created if necessary. If MODE is <CODE>'>>'</CODE>,
the file is opened for appending, again being created if necessary.
You can put a <CODE>'+'</CODE> in front of the <CODE>'>'</CODE> or <CODE>'<'</CODE> to indicate that
you want both read and write access to the file; thus <CODE>'+<'</CODE> is almost
always preferred for read/write updates--the <CODE>'+>'</CODE> mode would clobber the
file first. You can't usually use either read-write mode for updating
textfiles, since they have variable length records. See the <STRONG>-i</STRONG>
switch in <A HREF="../../lib/Pod/perlrun.html">the perlrun manpage</A> for a better approach. The file is created with
permissions of <CODE>0666</CODE> modified by the process' <A HREF="#item_umask"><CODE>umask</CODE></A> value.</P>
<P>These various prefixes correspond to the <CODE>fopen(3)</CODE> modes of <CODE>'r'</CODE>, <CODE>'r+'</CODE>,
<CODE>'w'</CODE>, <CODE>'w+'</CODE>, <CODE>'a'</CODE>, and <CODE>'a+'</CODE>.</P>
<P>In the 2-arguments (and 1-argument) form of the call the mode and
filename should be concatenated (in this order), possibly separated by
spaces. It is possible to omit the mode if the mode is <CODE>'<'</CODE>.</P>
<P>If the filename begins with <CODE>'|'</CODE>, the filename is interpreted as a
command to which output is to be piped, and if the filename ends with a
<CODE>'|'</CODE>, the filename is interpreted as a command which pipes output to
us. See <A HREF="../../lib/Pod/perlipc.html#using open() for ipc">Using open() for IPC in the perlipc manpage</A>
for more examples of this. (You are not allowed to <A HREF="#item_open"><CODE>open</CODE></A> to a command
that pipes both in <EM>and</EM> out, but see <A HREF="../../lib/IPC/Open2.html">the IPC::Open2 manpage</A>, <A HREF="../../lib/IPC/Open3.html">the IPC::Open3 manpage</A>,
and <A HREF="../../lib/Pod/perlipc.html#bidirectional communication with another process">Bidirectional Communication with Another Process in the perlipc manpage</A>
for alternatives.)</P>
<P>If MODE is <CODE>'|-'</CODE>, the filename is interpreted as a
command to which output is to be piped, and if MODE is
<CODE>'-|'</CODE>, the filename is interpreted as a command which pipes output to
us. In the 2-arguments (and 1-argument) form one should replace dash
(<CODE>'-'</CODE>) with the command. See <A HREF="../../lib/Pod/perlipc.html#using open() for ipc">Using open() for IPC in the perlipc manpage</A>
for more examples of this. (You are not allowed to <A HREF="#item_open"><CODE>open</CODE></A> to a command
that pipes both in <EM>and</EM> out, but see <A HREF="../../lib/IPC/Open2.html">the IPC::Open2 manpage</A>, <A HREF="../../lib/IPC/Open3.html">the IPC::Open3 manpage</A>,
and <A HREF="../../lib/Pod/perlipc.html#bidirectional communication">Bidirectional Communication in the perlipc manpage</A> for alternatives.)</P>
<P>In the 2-arguments (and 1-argument) form opening <CODE>'-'</CODE> opens STDIN
and opening <CODE>'>-'</CODE> opens STDOUT.</P>
<P>Open returns
nonzero upon success, the undefined value otherwise. If the <A HREF="#item_open"><CODE>open</CODE></A>
involved a pipe, the return value happens to be the pid of the
subprocess.</P>
<P>If you're unfortunate enough to be running Perl on a system that
distinguishes between text files and binary files (modern operating
systems don't care), then you should check out <A HREF="#binmode">binmode</A> for tips for
dealing with this. The key distinction between systems that need <A HREF="#item_binmode"><CODE>binmode</CODE></A>
and those that don't is their text file formats. Systems like Unix, MacOS, and
Plan9, which delimit lines with a single character, and which encode that
character in C as <CODE>"\n"</CODE>, do not need <A HREF="#item_binmode"><CODE>binmode</CODE></A>. The rest need it.</P>
<P>When opening a file, it's usually a bad idea to continue normal execution
if the request failed, so <A HREF="#item_open"><CODE>open</CODE></A> is frequently used in connection with
<A HREF="#item_die"><CODE>die</CODE></A>. Even if <A HREF="#item_die"><CODE>die</CODE></A> won't do what you want (say, in a CGI script,
where you want to make a nicely formatted error message (but there are
modules that can help with that problem)) you should always check
the return value from opening a file. The infrequent exception is when
working with an unopened filehandle is actually what you want to do.</P>
<P>Examples:</P>
<PRE>
$ARTICLE = 100;
open ARTICLE or die "Can't find article $ARTICLE: $!\n";
while (<ARTICLE>) {...</PRE>
<PRE>
open(LOG, '>>/usr/spool/news/twitlog'); # (log is reserved)
# if the open fails, output is discarded</PRE>
<PRE>
open(DBASE, '+<', 'dbase.mine') # open for update
or die "Can't open 'dbase.mine' for update: $!";</PRE>
<PRE>
open(DBASE, '+<dbase.mine') # ditto
or die "Can't open 'dbase.mine' for update: $!";</PRE>
<P>(The <CODE>$Config{longlongsize}</CODE> will be undefine if your system does
not support long longs.)</P>
<P></P>
<LI>
The integer formats <A HREF="../../lib/Pod/perlfunc.html#item_s"><CODE>s</CODE></A>, <CODE>S</CODE>, <CODE>i</CODE>, <CODE>I</CODE>, <CODE>l</CODE>, and <CODE>L</CODE>
are inherently non-portable between processors and operating systems
because they obey the native byteorder and endianness. For example a
4-byte integer 0x12345678 (305419896 decimal) be ordered natively
(arranged in and handled by the CPU registers) into bytes as
<PRE>
0x12 0x34 0x56 0x78 # little-endian
0x78 0x56 0x34 0x12 # big-endian</PRE>
<P>Basically, the Intel, Alpha, and VAX CPUs are little-endian, while
everybody else, for example Motorola m68k/88k, PPC, Sparc, HP PA,
Power, and Cray are big-endian. MIPS can be either: Digital used it
in little-endian mode; SGI uses it in big-endian mode.</P>
<P>The names `big-endian' and `little-endian' are comic references to
the classic ``Gulliver's Travels'' (via the paper ``On Holy Wars and a
Plea for Peace'' by Danny Cohen, USC/ISI IEN 137, April 1, 1980) and
the egg-eating habits of the Lilliputians.</P>
<P>Some systems may have even weirder byte orders such as</P>
<PRE>
0x56 0x78 0x12 0x34
0x34 0x12 0x78 0x56</PRE>
<P>You can see your system's preference with</P>
<PRE>
print join(" ", map { sprintf "%#02x", $_ }
unpack("C*",pack("L",0x12345678))), "\n";</PRE>
<P>The byteorder on the platform where Perl was built is also available
via <A HREF="../../lib/Config.html">the Config manpage</A>:</P>
<PRE>
use Config;
print $Config{byteorder}, "\n";</PRE>
<P>Byteorders <CODE>'1234'</CODE> and <CODE>'12345678'</CODE> are little-endian, <CODE>'4321'</CODE>
and <CODE>'87654321'</CODE> are big-endian.</P>
<P>If you want portable packed integers use the formats <CODE>n</CODE>, <CODE>N</CODE>,
<CODE>v</CODE>, and <CODE>V</CODE>, their byte endianness and size is known.
See also <A HREF="../../lib/Pod/perlport.html">the perlport manpage</A>.</P>
<P></P>
<LI>
Real numbers (floats and doubles) are in the native machine format only;
due to the multiplicity of floating formats around, and the lack of a
standard ``network'' representation, no facility for interchange has been
made. This means that packed floating point data written on one machine
may not be readable on another - even if both use IEEE floating point
arithmetic (as the endian-ness of the memory representation is not part
of the IEEE spec). See also <A HREF="../../lib/Pod/perlport.html">the perlport manpage</A>.
<P>Note that Perl uses doubles internally for all numeric calculation, and
converting from double into float and thence back to double again will
lose precision (i.e., <A HREF="#item_unpack"><CODE>unpack("f", pack("f", $foo)</CODE></A>) will not in general
equal $foo).</P>
<P></P>
<LI>
You must yourself do any alignment or padding by inserting for example
enough <CODE>'x'</CODE>es while packing. There is no way to <A HREF="#item_pack"><CODE>pack()</CODE></A> and <A HREF="#item_unpack"><CODE>unpack()</CODE></A>
could know where the bytes are going to or coming from. Therefore
<A HREF="#item_pack"><CODE>pack</CODE></A> (and <A HREF="#item_unpack"><CODE>unpack</CODE></A>) handle their output and input as flat
sequences of bytes.
<P></P>
<LI>
A comment in a TEMPLATE starts with <CODE>#</CODE> and goes to the end of line.
<P></P>
<LI>
If TEMPLATE requires more arguments to <A HREF="#item_pack"><CODE>pack()</CODE></A> than actually given, <A HREF="#item_pack"><CODE>pack()</CODE></A>
assumes additional <CODE>""</CODE> arguments. If TEMPLATE requires less arguments
to <A HREF="#item_pack"><CODE>pack()</CODE></A> than actually given, extra arguments are ignored.
<P></P></UL>
<P>Examples:</P>
<PRE>
$foo = pack("CCCC",65,66,67,68);
# foo eq "ABCD"
$foo = pack("C4",65,66,67,68);
# same thing
$foo = pack("U4",0x24b6,0x24b7,0x24b8,0x24b9);
# same thing with Unicode circled letters</PRE>
<PRE>
$foo = pack("ccxxcc",65,66,67,68);
# foo eq "AB\0\0CD"</PRE>
<PRE>
# note: the above examples featuring "C" and "c" are true
# only on ASCII and ASCII-derived systems such as ISO Latin 1
# and UTF-8. In EBCDIC the first example would be
# $foo = pack("CCCC",193,194,195,196);</PRE>
<PRE>
$foo = pack("s2",1,2);
# "\1\0\2\0" on little-endian
# "\0\1\0\2" on big-endian</PRE>
<PRE>
$foo = pack("a4","abcd","x","y","z");
# "abcd"</PRE>
<PRE>
$foo = pack("aaaa","abcd","x","y","z");
# "axyz"</PRE>
<PRE>
$foo = pack("a14","abcdefg");
# "abcdefg\0\0\0\0\0\0\0"</PRE>
<PRE>
$foo = pack("i9pl", gmtime);
# a real struct tm (on my system anyway)</PRE>
<PRE>
$utmp_template = "Z8 Z8 Z16 L";
$utmp = pack($utmp_template, @utmp1);
# a struct utmp (BSDish)</PRE>
<PRE>
@utmp2 = unpack($utmp_template, $utmp);
# "@utmp1" eq "@utmp2"</PRE>
<PRE>
sub bintodec {
unpack("N", pack("B32", substr("0" x 32 . shift, -32)));
}</PRE>
<PRE>
$foo = pack('sx2l', 12, 34);
# short 12, two zero bytes padding, long 34
$bar = pack('s@4l', 12, 34);
# short 12, zero fill to position 4, long 34
# $foo eq $bar</PRE>
<P>The same template may generally also be used in unpack().</P>
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
unless you are very careful. In addition, note that Perl's pipes use
stdio buffering, so you may need to set <CODE>$|</CODE> to flush your WRITEHANDLE
after each command, depending on the application.
<P>See <A HREF="../../lib/IPC/Open2.html">the IPC::Open2 manpage</A>, <A HREF="../../lib/IPC/Open3.html">the IPC::Open3 manpage</A>, and <A HREF="../../lib/Pod/perlipc.html#bidirectional communication">Bidirectional Communication in the perlipc manpage</A>
for examples of such things.</P>
<P>On systems that support a close-on-exec flag on files, the flag will be set
for the newly opened file descriptors as determined by the value of $^F.
See <A HREF="../../lib/Pod/perlvar.html#$^f">$^F in the perlvar manpage</A>.</P>
The <A HREF="#item_redo"><CODE>redo</CODE></A> command restarts the loop block without evaluating the
conditional again. The <A HREF="#item_continue"><CODE>continue</CODE></A> block, if any, is not executed. If
the LABEL is omitted, the command refers to the innermost enclosing
loop. This command is normally used by programs that want to lie to
themselves about what was just input:
<PRE>
# a simpleminded Pascal comment stripper
# (warning: assumes no { or } in strings)
LINE: while (<STDIN>) {
while (s|({.*}.*){.*}|$1 |) {}
s|{.*}| |;
if (s|{.*| |) {
$front = $_;
while (<STDIN>) {
if (/}/) { # end of comment?
s|^|$front\{|;
redo LINE;
}
}
}
print;
}</PRE>
<P><A HREF="#item_redo"><CODE>redo</CODE></A> cannot be used to retry a block which returns a value such as
<A HREF="#item_eval"><CODE>eval {}</CODE></A>, <A HREF="#item_sub"><CODE>sub {}</CODE></A> or <A HREF="#item_do"><CODE>do {}</CODE></A>, and should not be used to exit
a <A HREF="#item_grep"><CODE>grep()</CODE></A> or <A HREF="#item_map"><CODE>map()</CODE></A> operation.</P>
<P>Note that a block by itself is semantically identical to a loop
that executes once. Thus <A HREF="#item_redo"><CODE>redo</CODE></A> inside such a block will effectively
turn it into a looping construct.</P>
<P>See also <A HREF="#continue">continue</A> for an illustration of how <A HREF="#item_last"><CODE>last</CODE></A>, <A HREF="#item_next"><CODE>next</CODE></A>, and
Shifts the first value of the array off and returns it, shortening the
array by 1 and moving everything down. If there are no elements in the
array, returns the undefined value. If ARRAY is omitted, shifts the
<CODE>@_</CODE> array within the lexical scope of subroutines and formats, and the
<CODE>@ARGV</CODE> array at file scopes or within the lexical scopes established by
the <CODE>eval ''</CODE>, <CODE>BEGIN {}</CODE>, <CODE>INIT {}</CODE>, <CODE>CHECK {}</CODE>, and <CODE>END {}</CODE>
constructs.
<P>See also <A HREF="#item_unshift"><CODE>unshift</CODE></A>, <A HREF="#item_push"><CODE>push</CODE></A>, and <A HREF="#item_pop"><CODE>pop</CODE></A>. <CODE>Shift()</CODE> and <A HREF="#item_unshift"><CODE>unshift</CODE></A> do the
same thing to the left end of an array that <A HREF="#item_pop"><CODE>pop</CODE></A> and <A HREF="#item_push"><CODE>push</CODE></A> do to the
Causes the script to sleep for EXPR seconds, or forever if no EXPR.
May be interrupted if the process receives a signal such as <CODE>SIGALRM</CODE>.
Returns the number of seconds actually slept. You probably cannot
mix <A HREF="#item_alarm"><CODE>alarm</CODE></A> and <A HREF="#item_sleep"><CODE>sleep</CODE></A> calls, because <A HREF="#item_sleep"><CODE>sleep</CODE></A> is often implemented
using <A HREF="#item_alarm"><CODE>alarm</CODE></A>.
<P>On some older systems, it may sleep up to a full second less than what
you requested, depending on how it counts seconds. Most modern systems
always sleep the full amount. They may appear to sleep longer than that,
however, because your process might not be scheduled right away in a
busy multitasking system.</P>
<P>For delays of finer granularity than one second, you may use Perl's
<A HREF="#item_syscall"><CODE>syscall</CODE></A> interface to access <CODE>setitimer(2)</CODE> if your system supports
it, or else see <A HREF="#select">select</A> above. The Time::HiRes module from CPAN
may also help.</P>
<P>See also the POSIX module's <CODE>sigpause</CODE> function.</P>
Sorts the LIST and returns the sorted list value. If SUBNAME or BLOCK
is omitted, <A HREF="#item_sort"><CODE>sort</CODE></A>s in standard string comparison order. If SUBNAME is
specified, it gives the name of a subroutine that returns an integer
less than, equal to, or greater than <CODE>0</CODE>, depending on how the elements
of the list are to be ordered. (The <CODE><=></CODE> and <CODE>cmp</CODE>
operators are extremely useful in such routines.) SUBNAME may be a
scalar variable name (unsubscripted), in which case the value provides
the name of (or a reference to) the actual subroutine to use. In place
of a SUBNAME, you can provide a BLOCK as an anonymous, in-line sort
subroutine.
<P>If the subroutine's prototype is <CODE>($$)</CODE>, the elements to be compared
are passed by reference in <CODE>@_</CODE>, as for a normal subroutine. This is
slower than unprototyped subroutines, where the elements to be
compared are passed into the subroutine
as the package global variables $a and $b (see example below). Note that
in the latter case, it is usually counter-productive to declare $a and
$b as lexicals.</P>
<P>In either case, the subroutine may not be recursive. The values to be
compared are always passed by reference, so don't modify them.</P>
<P>You also cannot exit out of the sort block or subroutine using any of the
loop control operators described in <A HREF="../../lib/Pod/perlsyn.html">the perlsyn manpage</A> or with <A HREF="#item_goto"><CODE>goto</CODE></A>.</P>
<P>When <CODE>use locale</CODE> is in effect, <A HREF="#item_sort"><CODE>sort LIST</CODE></A> sorts LIST according to the
current collation locale. See <A HREF="../../lib/Pod/perllocale.html">the perllocale manpage</A>.</P>
<P>The pattern <CODE>/PATTERN/</CODE> may be replaced with an expression to specify
patterns that vary at runtime. (To do runtime compilation only once,
use <CODE>/$variable/o</CODE>.)</P>
<P>As a special case, specifying a PATTERN of space (<CODE>' '</CODE>) will split on
white space just as <A HREF="#item_split"><CODE>split</CODE></A> with no arguments does. Thus, <A HREF="#item_split"><CODE>split(' ')</CODE></A> can
be used to emulate <STRONG>awk</STRONG>'s default behavior, whereas <A HREF="#item_split"><CODE>split(/ /)</CODE></A>
will give you as many null initial fields as there are leading spaces.
A <A HREF="#item_split"><CODE>split</CODE></A> on <CODE>/\s+/</CODE> is like a <A HREF="#item_split"><CODE>split(' ')</CODE></A> except that any leading
whitespace produces a null first field. A <A HREF="#item_split"><CODE>split</CODE></A> with no arguments
really does a <A HREF="#item_split"><CODE>split(' ', $_)</CODE></A> internally.</P>
<P>Example:</P>
<PRE>
open(PASSWD, '/etc/passwd');
while (<PASSWD>) {
($login, $passwd, $uid, $gid,
$gcos, $home, $shell) = split(/:/);
#...
}</PRE>
<P>(Note that $shell above will still have a newline on it. See <A HREF="#chop">chop</A>,
<A HREF="#chomp">chomp</A>, and <A HREF="#join">join</A>.)</P>
<P></P>
<DT><STRONG><A NAME="item_sprintf">sprintf FORMAT, LIST</A></STRONG><BR>
<DD>
Returns a string formatted by the usual <A HREF="#item_printf"><CODE>printf</CODE></A> conventions of the
C library function <A HREF="#item_sprintf"><CODE>sprintf</CODE></A>. See <A HREF="#item_sprintf">sprintf(3)</A> or <A HREF="#item_printf">printf(3)</A>
on your system for an explanation of the general principles.
<P>Perl does its own <A HREF="#item_sprintf"><CODE>sprintf</CODE></A> formatting--it emulates the C
function <A HREF="#item_sprintf"><CODE>sprintf</CODE></A>, but it doesn't use it (except for floating-point
numbers, and even then only the standard modifiers are allowed). As a
result, any non-standard extensions in your local <A HREF="#item_sprintf"><CODE>sprintf</CODE></A> are not
available from Perl.</P>
<P>Perl's <A HREF="#item_sprintf"><CODE>sprintf</CODE></A> permits the following universally-known conversions:</P>
<PRE>
%% a percent sign
%c a character with the given number
%s a string
%d a signed integer, in decimal
%u an unsigned integer, in decimal
%o an unsigned integer, in octal
%x an unsigned integer, in hexadecimal
%e a floating-point number, in scientific notation
%f a floating-point number, in fixed decimal notation
%g a floating-point number, in %e or %f notation</PRE>
<P>In addition, Perl permits the following widely-supported conversions:</P>
<PRE>
%X like %x, but using upper-case letters
%E like %e, but using an upper-case "E"
%G like %g, but with an upper-case "E" (if applicable)
%b an unsigned integer, in binary
%p a pointer (outputs the Perl value's address in hexadecimal)
%n special: *stores* the number of characters output so far
into the next variable in the parameter list</PRE>
<P>Finally, for backward (and we do mean ``backward'') compatibility, Perl
permits these unnecessary but widely-supported conversions:</P>
<PRE>
%i a synonym for %d
%D a synonym for %ld
%U a synonym for %lu
%O a synonym for %lo
%F a synonym for %f</PRE>
<P>Perl permits the following universally-known flags between the <CODE>%</CODE>
and the conversion letter:</P>
<PRE>
space prefix positive number with a space
+ prefix positive number with a plus sign
- left-justify within the field
0 use zeros, not spaces, to right-justify
# prefix non-zero octal with "0", non-zero hex with "0x"
number minimum field width
.number "precision": digits after decimal point for
floating-point, max length for string, minimum length
for integer
l interpret integer as C type "long" or "unsigned long"
h interpret integer as C type "short" or "unsigned short"
If no flags, interpret integer as C type "int" or "unsigned"</PRE>
<P>There are also two Perl-specific flags:</P>
<PRE>
V interpret integer as Perl's standard integer type
v interpret string as a vector of integers, output as
numbers separated either by dots, or by an arbitrary
string received from the argument list when the flag
is preceded by C<*></PRE>
<P>Where a number would appear in the flags, an asterisk (<CODE>*</CODE>) may be
used instead, in which case Perl uses the next item in the parameter
list as the given number (that is, as the field width or precision).
If a field width obtained through <CODE>*</CODE> is negative, it has the same
effect as the <CODE>-</CODE> flag: left-justification.</P>
<P>The <CODE>v</CODE> flag is useful for displaying ordinal values of characters
in arbitrary strings:</P>
<PRE>
printf "version is v%vd\n", $^V; # Perl's version
printf "address is %*vX\n", ":", $addr; # IPv6 address
printf "bits are %*vb\n", " ", $bits; # random bitstring</PRE>
<P>If <CODE>use locale</CODE> is in effect, the character used for the decimal
point in formatted real numbers is affected by the LC_NUMERIC locale.
See <A HREF="../../lib/Pod/perllocale.html">the perllocale manpage</A>.</P>
Attempts to read LENGTH bytes of data into variable SCALAR from the
specified FILEHANDLE, using the system call read(2). It bypasses stdio,
so mixing this with other kinds of reads, <A HREF="#item_print"><CODE>print</CODE></A>, <A HREF="#item_write"><CODE>write</CODE></A>,
<A HREF="#item_seek"><CODE>seek</CODE></A>, <A HREF="#item_tell"><CODE>tell</CODE></A>, or <A HREF="#item_eof"><CODE>eof</CODE></A> can cause confusion because stdio
usually buffers data. Returns the number of bytes actually read, <CODE>0</CODE>
at end of file, or undef if there was an error. SCALAR will be grown or
shrunk so that the last byte actually read is the last byte of the
scalar after the read.
<P>An OFFSET may be specified to place the read data at some place in the
string other than the beginning. A negative OFFSET specifies
placement at that many bytes counting backwards from the end of the
string. A positive OFFSET greater than the length of SCALAR results
in the string being padded to the required size with <CODE>"\0"</CODE> bytes before
the result of the read is appended.</P>
<P>There is no <CODE>syseof()</CODE> function, which is ok, since <A HREF="#item_eof"><CODE>eof()</CODE></A> doesn't work
very well on device files (like ttys) anyway. Use <A HREF="#item_sysread"><CODE>sysread()</CODE></A> and check
for a return value for 0 to decide whether you're done.</P>
Sets FILEHANDLE's system position using the system call lseek(2). It
bypasses stdio, so mixing this with reads (other than <A HREF="#item_sysread"><CODE>sysread</CODE></A>),
<A HREF="#item_print"><CODE>print</CODE></A>, <A HREF="#item_write"><CODE>write</CODE></A>, <A HREF="#item_seek"><CODE>seek</CODE></A>, <A HREF="#item_tell"><CODE>tell</CODE></A>, or <A HREF="#item_eof"><CODE>eof</CODE></A> may cause confusion.
FILEHANDLE may be an expression whose value gives the name of the
filehandle. The values for WHENCE are <CODE>0</CODE> to set the new position to
POSITION, <CODE>1</CODE> to set the it to the current position plus POSITION,
and <CODE>2</CODE> to set it to EOF plus POSITION (typically negative). For
WHENCE, you may also use the constants <CODE>SEEK_SET</CODE>, <CODE>SEEK_CUR</CODE>, and
<CODE>SEEK_END</CODE> (start of the file, current position, end of the file)
from the Fcntl module.
<P>Returns the new position, or the undefined value on failure. A position
of zero is returned as the string <CODE>"0 but true"</CODE>; thus <A HREF="#item_sysseek"><CODE>sysseek</CODE></A> returns
true on success and false on failure, yet you can still easily determine
Does exactly the same thing as <A HREF="#item_exec"><CODE>exec LIST</CODE></A>, except that a fork is
done first, and the parent process waits for the child process to
complete. Note that argument processing varies depending on the
number of arguments. If there is more than one argument in LIST,
or if LIST is an array with more than one value, starts the program
given by the first element of the list with arguments given by the
rest of the list. If there is only one scalar argument, the argument
is checked for shell metacharacters, and if there are any, the
entire argument is passed to the system's command shell for parsing
(this is <CODE>/bin/sh -c</CODE> on Unix platforms, but varies on other
platforms). If there are no shell metacharacters in the argument,
it is split into words and passed directly to <CODE>execvp</CODE>, which is
more efficient.
<P>Beginning with v5.6.0, Perl will attempt to flush all files opened for
output before any operation that may do a fork, but this may not be
supported on some platforms (see <A HREF="../../lib/Pod/perlport.html">the perlport manpage</A>). To be safe, you may need
to set <CODE>$|</CODE> ($AUTOFLUSH in English) or call the <A HREF="../../lib/Pod/perlvar.html#item_autoflush"><CODE>autoflush()</CODE></A> method
of <CODE>IO::Handle</CODE> on any open handles.</P>
<P>The return value is the exit status of the program as
returned by the <A HREF="#item_wait"><CODE>wait</CODE></A> call. To get the actual exit value divide by
256. See also <A HREF="#exec">exec</A>. This is <EM>not</EM> what you want to use to capture
the output from a command, for that you should use merely backticks or
<A HREF="#item_qx/"><CODE>qx//</CODE></A>, as described in <A HREF="../../lib/Pod/perlop.html#`string`">`STRING` in the perlop manpage</A>. Return value of -1
indicates a failure to start the program (inspect $! for the reason).</P>
<P>Like <A HREF="#item_exec"><CODE>exec</CODE></A>, <A HREF="#item_system"><CODE>system</CODE></A> allows you to lie to a program about its name if
you use the <A HREF="#item_system"><CODE>system PROGRAM LIST</CODE></A> syntax. Again, see <A HREF="#exec">exec</A>.</P>
<P>Because <A HREF="#item_system"><CODE>system</CODE></A> and backticks block <CODE>SIGINT</CODE> and <CODE>SIGQUIT</CODE>, killing the
program they're running doesn't actually interrupt your program.</P>
<PRE>
@args = ("command", "arg1", "arg2");
system(@args) == 0
or die "system @args failed: $?"</PRE>
<P>You can check all the failure possibilities by inspecting
<CODE>$?</CODE> like this:</P>
<PRE>
$exit_value = $? >> 8;
$signal_num = $? & 127;
$dumped_core = $? & 128;</PRE>
<P>When the arguments get executed via the system shell, results
and return codes will be subject to its quirks and capabilities.
See <A HREF="../../lib/Pod/perlop.html#`string`">`STRING` in the perlop manpage</A> and <A HREF="#exec">exec</A> for details.</P>
Attempts to write LENGTH bytes of data from variable SCALAR to the
specified FILEHANDLE, using the system call write(2). If LENGTH
is not specified, writes whole SCALAR. It bypasses stdio, so mixing
this with reads (other than <A HREF="#item_sysread"><CODE>sysread())</CODE></A>, <A HREF="#item_print"><CODE>print</CODE></A>, <A HREF="#item_write"><CODE>write</CODE></A>,
<A HREF="#item_seek"><CODE>seek</CODE></A>, <A HREF="#item_tell"><CODE>tell</CODE></A>, or <A HREF="#item_eof"><CODE>eof</CODE></A> may cause confusion because stdio
usually buffers data. Returns the number of bytes actually written,
or <A HREF="#item_undef"><CODE>undef</CODE></A> if there was an error. If the LENGTH is greater than
the available data in the SCALAR after the OFFSET, only as much
data as is available will be written.
<P>An OFFSET may be specified to write the data from some part of the
string other than the beginning. A negative OFFSET specifies writing
that many bytes counting backwards from the end of the string. In the
case the SCALAR is empty you can use OFFSET but only zero offset.</P>
Returns the number of non-leap seconds since whatever time the system
considers to be the epoch (that's 00:00:00, January 1, 1904 for MacOS,
and 00:00:00 UTC, January 1, 1970 for most other systems).
Suitable for feeding to <A HREF="#item_gmtime"><CODE>gmtime</CODE></A> and <A HREF="#item_localtime"><CODE>localtime</CODE></A>.
<P>For measuring time in better granularity than one second,
you may use either the Time::HiRes module from CPAN, or
if you have gettimeofday(2), you may be able to use the
<A HREF="#item_syscall"><CODE>syscall</CODE></A> interface of Perl, see <A HREF="../../lib/Pod/perlfaq8.html">the perlfaq8 manpage</A> for details.</P>
<P>Note the LIST is prepended whole, not one element at a time, so the
prepended elements stay in the same order. Use <A HREF="#item_reverse"><CODE>reverse</CODE></A> to do the
reverse.</P>
<P></P>
<DT><STRONG><A NAME="item_use">use Module VERSION LIST</A></STRONG><BR>
<DD>
<DT><STRONG>use Module VERSION</STRONG><BR>
<DD>
<DT><STRONG>use Module LIST</STRONG><BR>
<DD>
<DT><STRONG>use Module</STRONG><BR>
<DD>
<DT><STRONG>use VERSION</STRONG><BR>
<DD>
Imports some semantics into the current package from the named module,
generally by aliasing certain subroutine or variable names into your
package. It is exactly equivalent to
<PRE>
BEGIN { require Module; import Module LIST; }</PRE>
<P>except that Module <EM>must</EM> be a bareword.</P>
<P>VERSION, which can be specified as a literal of the form v5.6.1, demands
that the current version of Perl (<CODE>$^V</CODE> or $PERL_VERSION) be at least
as recent as that version. (For compatibility with older versions of Perl,
a numeric literal will also be interpreted as VERSION.) If the version
of the running Perl interpreter is less than VERSION, then an error
message is printed and Perl exits immediately without attempting to
parse the rest of the file. Compare with <A HREF="#require">require</A>, which can do a
similar check at run time.</P>
<PRE>
use v5.6.1; # compile time version check
use 5.6.1; # ditto
use 5.005_03; # float version allowed for compatibility</PRE>
<P>This is often useful if you need to check the current Perl version before
<A HREF="#item_use"><CODE>use</CODE></A>ing library modules that have changed in incompatible ways from
older versions of Perl. (We try not to do this more than we have to.)</P>
<P>The <CODE>BEGIN</CODE> forces the <A HREF="#item_require"><CODE>require</CODE></A> and <A HREF="#item_import"><CODE>import</CODE></A> to happen at compile time. The
<A HREF="#item_require"><CODE>require</CODE></A> makes sure the module is loaded into memory if it hasn't been
yet. The <A HREF="#item_import"><CODE>import</CODE></A> is not a builtin--it's just an ordinary static method
call into the <CODE>Module</CODE> package to tell the module to import the list of
features back into the current package. The module can implement its
<A HREF="#item_import"><CODE>import</CODE></A> method any way it likes, though most modules just choose to
derive their <A HREF="#item_import"><CODE>import</CODE></A> method via inheritance from the <CODE>Exporter</CODE> class that
is defined in the <CODE>Exporter</CODE> module. See <A HREF="../../lib/Exporter.html">the Exporter manpage</A>. If no <A HREF="#item_import"><CODE>import</CODE></A>
method can be found then the call is skipped.</P>
<P>If you don't want your namespace altered, explicitly supply an empty list:</P>
<PRE>
use Module ();</PRE>
<P>That is exactly equivalent to</P>
<PRE>
BEGIN { require Module }</PRE>
<P>If the VERSION argument is present between Module and LIST, then the
<A HREF="#item_use"><CODE>use</CODE></A> will call the VERSION method in class Module with the given
version as an argument. The default VERSION method, inherited from
the UNIVERSAL class, croaks if the given version is larger than the
value of the variable <CODE>$Module::VERSION</CODE>.</P>
<P>Again, there is a distinction between omitting LIST (<A HREF="#item_import"><CODE>import</CODE></A> called
with no arguments) and an explicit empty LIST <CODE>()</CODE> (<A HREF="#item_import"><CODE>import</CODE></A> not
called). Note that there is no comma after VERSION!</P>
<P>Because this is a wide-open interface, pragmas (compiler directives)
are also implemented this way. Currently implemented pragmas are:</P>
<PRE>
use integer;
use diagnostics;
use sigtrap qw(SEGV BUS);
use strict qw(subs vars refs);
use subs qw(afunc blurfl);
use warnings qw(all);</PRE>
<P>Some of these pseudo-modules import semantics into the current
block scope (like <CODE>strict</CODE> or <CODE>integer</CODE>, unlike ordinary modules,
which import symbols into the current package (which are effective
through the end of the file).</P>
<P>There's a corresponding <A HREF="#item_no"><CODE>no</CODE></A> command that unimports meanings imported
by <A HREF="#item_use"><CODE>use</CODE></A>, i.e., it calls <CODE>unimport Module LIST</CODE> instead of <A HREF="#item_import"><CODE>import</CODE></A>.</P>
<PRE>
no integer;
no strict 'refs';
no warnings;</PRE>
<P>If no <CODE>unimport</CODE> method can be found the call fails with a fatal error.</P>
<P>See <A HREF="../../lib/Pod/perlmod.html">the perlmod manpage</A> for a list of standard modules and pragmas.</P>