PERLFUNC(1) PERLFUNC(1)
perlfunc - Perl builtin functions
The functions in this section can serve as terms in an expression. They
fall into two major categories: list operators and named unary operators.
These differ in their precedence relationship with a following comma.
(See the precedence table in the perlop manpage.) List operators take
more than one argument, while unary operators can never take more than
one argument. Thus, a comma terminates the argument of a unary operator,
but merely separates the arguments of a list operator. A unary operator
generally provides a scalar context to its argument, while a list
operator may provide either scalar and list contexts for its arguments.
If it does both, the scalar arguments will be first, and the list
argument will follow. (Note that there can ever be only one list
argument.) For instance, splice() has three scalar arguments followed by
a list.
In the syntax descriptions that follow, list operators that expect a list
(and provide list context for the elements of the list) are shown with
LIST as an argument. Such a list may consist of any combination of
scalar arguments or list values; the list values will be included in the
list as if each individual element were interpolated at that point in the
list, forming a longer single-dimensional list value. Elements of the
LIST should be separated by commas.
Any function in the list below may be used either with or without
parentheses around its arguments. (The syntax descriptions omit the
parentheses.) If you use the parentheses, the simple (but occasionally
surprising) rule is this: It LOOKS like a function, therefore it IS a
function, and precedence doesn't matter. Otherwise it's a list operator
or unary operator, and precedence does matter. And whitespace between
the function and left parenthesis doesn't count--so you need to be
careful sometimes:
print 1+2+4; # Prints 7.
print(1+2) + 4; # Prints 3.
print (1+2)+4; # Also prints 3!
print +(1+2)+4; # Prints 7.
print ((1+2)+4); # Prints 7.
If you run Perl with the -w switch it can warn you about this. For
example, the third line above produces:
print (...) interpreted as function at - line 1.
Useless use of integer addition in void context at - line 1.
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.
Page 1
PERLFUNC(1) PERLFUNC(1)
Remember the following rule:
THERE IS NO GENERAL RULE FOR CONVERTING A LIST INTO A SCALAR!
Each operator and function decides which sort of value it would be most
appropriate to return in a scalar context. Some operators return the
length of the list that would have been returned in a 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.
Perl Functions by Category [Toc] [Back]
Here are Perl's functions (including things that look like functions,
like some of the keywords and named operators) arranged by category.
Some functions appear in more than one place.
Functions for SCALARs or strings
chomp, chop, chr, crypt, hex, index, lc, lcfirst, length, oct, ord,
pack, q/STRING/, qq/STRING/, reverse, rindex, sprintf, substr,
tr///, uc, ucfirst, y///
Regular expressions and pattern matching
m//, pos, quotemeta, s///, split, study
Numeric functions
abs, atan2, cos, exp, hex, int, log, oct, rand, sin, sqrt, srand
Functions for real @ARRAYs
pop, push, shift, splice, unshift
Functions for list data
grep, join, map, qw/STRING/, reverse, sort, unpack
Functions for real %HASHes
delete, each, exists, keys, values
Input and output functions
binmode, close, closedir, dbmclose, dbmopen, die, eof, fileno,
flock, format, getc, print, printf, read, readdir, rewinddir, seek,
seekdir, select, syscall, sysread, sysseek, syswrite, tell, telldir,
truncate, warn, write
Functions for fixed length data or records
pack, read, syscall, sysread, syswrite, unpack, vec
Functions for filehandles, files, or directories
-X, chdir, chmod, chown, chroot, fcntl, glob, ioctl, link, lstat,
mkdir, open, opendir, readlink, rename, rmdir, stat, symlink, umask,
unlink, utime
Page 2
PERLFUNC(1) PERLFUNC(1)
Keywords related to the control flow of your perl program
caller, continue, die, do, dump, eval, exit, goto, last, next, redo,
return, sub, wantarray
Keywords related to scoping
caller, import, local, my, package, use
Miscellaneous functions
defined, dump, eval, formline, local, my, reset, scalar, undef,
wantarray
Functions for processes and process groups
alarm, exec, fork, getpgrp, getppid, getpriority, kill, pipe,
qx/STRING/, setpgrp, setpriority, sleep, system, times, wait,
waitpid
Keywords related to perl modules
do, import, no, package, require, use
Keywords related to classes and object-orientedness
bless, dbmclose, dbmopen, package, ref, tie, tied, untie, use
Low-level socket functions
accept, bind, connect, getpeername, getsockname, getsockopt, listen,
recv, send, setsockopt, shutdown, socket, socketpair
System V interprocess communication functions
msgctl, msgget, msgrcv, msgsnd, semctl, semget, semop, shmctl,
shmget, shmread, shmwrite
Fetching user and group info
endgrent, endhostent, endnetent, endpwent, getgrent, getgrgid,
getgrnam, getlogin, getpwent, getpwnam, getpwuid, setgrent, setpwent
Fetching network info
endprotoent, endservent, gethostbyaddr, gethostbyname, gethostent,
getnetbyaddr, getnetbyname, getnetent, getprotobyname,
getprotobynumber, getprotoent, getservbyname, getservbyport,
getservent, sethostent, setnetent, setprotoent, setservent
Time-related functions
gmtime, localtime, time, times
Functions new in perl5
abs, bless, chomp, chr, exists, formline, glob, import, lc, lcfirst,
map, my, no, prototype, qx, qw, readline, readpipe, ref, sub*,
sysopen, tie, tied, uc, ucfirst, untie, use
* - sub was a keyword in perl4, but in perl5 it is an operator which
can be used in expressions.
Page 3
PERLFUNC(1) PERLFUNC(1)
Functions obsoleted in perl5
dbmclose, dbmopen
Alphabetical Listing of Perl Functions [Toc] [Back]
-X FILEHANDLE
-X EXPR
-X 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 $_, except for
-t, which tests STDIN. Unless otherwise documented, it returns 1
for TRUE and '' 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:
-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.
-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.
-e File exists.
-z File has zero size.
-s File has nonzero size (returns size).
-f File is a plain file.
-d File is a directory.
-l File is a symbolic link.
-p File is a named pipe (FIFO).
-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.
-u File has setuid bit set.
-g File has setgid bit set.
-k File has sticky bit set.
-T File is a text file.
-B File is a binary file (opposite of -T).
Page 4
PERLFUNC(1) PERLFUNC(1)
-M Age of file in days when script started.
-A Same for access time.
-C Same for inode change time.
The interpretation of the file permission operators -r, -R, -w,
-W, -x, and -X is 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. Also note that, for
the superuser, -r, -R, -w, and -W always return 1, and -x and -X
return 1 if any execute bit is set in the mode. Scripts run by
the superuser may thus need to do a stat() to determine the
actual mode of the file, or temporarily set the uid to something
else.
Example:
while (<>) {
chop;
next unless -f $_; # ignore specials
...
}
Note that -s/a/b/ does not do a negated substitution. Saying
-exp($foo) still works as expected, however--only single letters
following a minus are interpreted as file tests.
The -T and -B 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 odd
characters (>30%) are found, it's a -B file, otherwise it's a -T
file. Also, any file containing null in the first block is
considered a binary file. If -T or -B is used on a filehandle,
the current stdio buffer is examined rather than the first block.
Both -T and -B 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
-T test, on most occasions you want to use a -f against the file
first, as in next unless -f $file && -T $file.
If any of the file tests (or either the stat() or lstat()
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 -t, and you need to remember that lstat() and
-l will leave values in the stat structure for the symbolic link,
not the real file.) Example:
print "Can do.\n" if -r $a || -w _ || -x _;
Page 5
PERLFUNC(1) PERLFUNC(1)
stat($filename);
print "Readable\n" if -r _;
print "Writable\n" if -w _;
print "Executable\n" if -x _;
print "Setuid\n" if -u _;
print "Setgid\n" if -g _;
print "Sticky\n" if -k _;
print "Text\n" if -T _;
print "Binary\n" if -B _;
abs VALUE
abs Returns the absolute value of its argument. If VALUE is omitted,
uses $_.
accept NEWSOCKET,GENERICSOCKET
Accepts an incoming socket connect, just as the accept(2) system
call does. Returns the packed address if it succeeded, FALSE
otherwise. See example in the section on Sockets: Client/Server
Communication in the perlipc manpage.
alarm SECONDS
alarm Arranges to have a SIGALRM delivered to this process after the
specified number of seconds have elapsed. If SECONDS is not
specified, the value stored in $_ is used. (On some machines,
unfortunately, the elapsed time may be up to one second less than
you specified because of how seconds are counted.) Only one
timer may be counting at once. Each call disables the previous
timer, and an argument of 0 may be supplied to cancel the
previous timer without starting a new one. The returned value is
the amount of time remaining on the previous timer.
For delays of finer granularity than one second, you may use
Perl's syscall() interface to access setitimer(2) if your system
supports it, or else see the select() entry elsewhere in this
document . It is usually a mistake to intermix alarm() and
sleep() calls.
If you want to use alarm() to time out a system call you need to
use an eval/die pair. You can't rely on the alarm causing the
system call to fail with $! set to EINTR because Perl sets up
signal handlers to restart system calls on some systems. Using
eval/die always works.
Page 6
PERLFUNC(1) PERLFUNC(1)
eval {
local $SIG{ALRM} = sub { die "alarm\n" }; # NB \n required
alarm $timeout;
$nread = sysread SOCKET, $buffer, $size;
alarm 0;
};
die if $@ && $@ ne "alarm\n"; # propagate errors
if ($@) {
# timed out
}
else {
# didn't
}
atan2 Y,X
Returns the arctangent of Y/X in the range -pi to pi.
For the tangent operation, you may use the POSIX::tan() function,
or use the familiar relation:
sub tan { sin($_[0]) / cos($_[0]) }
bind SOCKET,NAME
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 packed address of the appropriate type for the
socket. See the examples in the section on Sockets:
Client/Server Communication in the perlipc manpage.
binmode FILEHANDLE
Arranges for the file to be read or written in "binary" mode in
operating systems that distinguish between binary and text files.
Files that are not in binary mode have CR LF sequences translated
to LF on input and LF translated to CR LF on output. Binmode has
no effect under Unix; in MS-DOS and similarly archaic systems, it
may be imperative--otherwise your MS-DOS-damaged C library may
mangle your file. The key distinction between systems that need
binmode and those that don't is their text file formats. Systems
like Unix and Plan9 that delimit lines with a single character,
and that encode that character in C as '\n', do not need binmode.
The rest need it. If FILEHANDLE is an expression, the value is
taken as the name of the filehandle.
bless REF,CLASSNAME
bless REF
This function tells the thingy referenced by REF that it is now
an object in the CLASSNAME package--or the current package if no
CLASSNAME is specified, which is often the case. It returns the
reference for convenience, because a bless() is often the last
Page 7
PERLFUNC(1) PERLFUNC(1)
thing in a constructor. Always use the two-argument version if
the function doing the blessing might be inherited by a derived
class. See the perlobj manpage for more about the blessing (and
blessings) of objects.
caller EXPR
caller Returns the context of the current subroutine call. In a scalar
context, returns the caller's package name if there is a caller,
that is, if we're in a subroutine or eval() or require(), and the
undefined value otherwise. In a list context, returns
($package, $filename, $line) = caller;
With EXPR, it returns some extra information that the debugger
uses to print a stack trace. The value of EXPR indicates how
many call frames to go back before the current one.
($package, $filename, $line, $subroutine,
$hasargs, $wantarray, $evaltext, $is_require) = caller($i);
Here $subroutine may be "(eval)" if the frame is not a subroutine
call, but an eval. In such a case additional elements $evaltext
and $is_require are set: $is_require is true if the frame is
created by a require or use statement, $evaltext contains the
text of the eval EXPR statement. In particular, for a eval BLOCK
statement, $filename is "(eval)", but $evaltext is undefined.
(Note also that each use statement creates a require frame inside
an eval EXPR) frame.
Furthermore, when called from within the DB package, caller
returns more detailed information: it sets the list variable
@DB::args to be the arguments with which the subroutine was
invoked.
chdir EXPR
Changes the working directory to EXPR, if possible. If EXPR is
omitted, changes to home directory. Returns TRUE upon success,
FALSE otherwise. See example under die().
chmod LIST
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 number, and which definitely should not a string of octal
digits: 0644 is okay, '0644' is not. Returns the number of
files successfully changed. See also the oct entry elsewhere in
this document if all you have is a string.
Page 8
PERLFUNC(1) PERLFUNC(1)
$cnt = chmod 0755, 'foo', 'bar';
chmod 0755, @executables;
$mode = '0644'; chmod $mode, 'foo'; # !!! sets mode to --w----r-T
$mode = '0644'; chmod oct($mode), 'foo'; # this is better
$mode = 0644; chmod $mode, 'foo'; # this is best
chomp VARIABLE
chomp LIST
chomp This is a slightly safer version of the chop entry elsewhere in
this document . It removes any line ending that corresponds to
the current value of $/ (also known as $INPUT_RECORD_SEPARATOR in
the English 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 ($/ = ""), it removes all trailing newlines from the string.
If VARIABLE is omitted, it chomps $_. Example:
while (<>) {
chomp; # avoid \n on last field
@array = split(/:/);
...
}
You can actually chomp anything that's an lvalue, including an
assignment:
chomp($cwd = `pwd`);
chomp($answer = <STDIN>);
If you chomp a list, each element is chomped, and the total
number of characters removed is returned.
chop VARIABLE
chop LIST
chop Chops off the last character of a string and returns the
character chopped. It's used primarily to remove the newline
from the end of an input record, but is much more efficient than
s/\n// because it neither scans nor copies the string. If
VARIABLE is omitted, chops $_. Example:
while (<>) {
chop; # avoid \n on last field
@array = split(/:/);
...
}
Page 9
PERLFUNC(1) PERLFUNC(1)
You can actually chop anything that's an lvalue, including an
assignment:
chop($cwd = `pwd`);
chop($answer = <STDIN>);
If you chop a list, each element is chopped. Only the value of
the last chop is returned.
Note that chop returns the last character. To return all but the
last character, use substr($string, 0, -1).
chown LIST
Changes the owner (and group) of a list of files. The first two
elements of the list must be the NUMERICAL uid and gid, in that
order. Returns the number of files successfully changed.
$cnt = chown $uid, $gid, 'foo', 'bar';
chown $uid, $gid, @filenames;
Here's an example that looks up nonnumeric uids in the passwd
file:
print "User: ";
chop($user = <STDIN>);
print "Files: "
chop($pattern = <STDIN>);
($login,$pass,$uid,$gid) = getpwnam($user)
or die "$user not in passwd file";
@ary = <${pattern}>; # expand filenames
chown $uid, $gid, @ary;
On most systems, you are not allowed to change the ownership of
the file unless you're the superuser, although you should be able
to change the group to any of your secondary groups. On insecure
systems, these restrictions may be relaxed, but this is not a
portable assumption.
chr NUMBER
chr Returns the character represented by that NUMBER in the character
set. For example, chr(65) is "A" in ASCII. For the reverse, use
the ord entry elsewhere in this document .
If NUMBER is omitted, uses $_.
chroot FILENAME
Page 10
PERLFUNC(1) PERLFUNC(1)
chroot This function works as the system call by the same name: it makes
the named directory the new root directory for all further
pathnames that begin with a "/" by your process and all of its
children. (It doesn't change your current working directory,
which is unaffected.) For security reasons, this call is
restricted to the superuser. If FILENAME is omitted, does chroot
to $_.
close FILEHANDLE
Closes the file or pipe associated with the file handle,
returning TRUE only if stdio successfully flushes buffers and
closes the system file descriptor.
You don't have to close FILEHANDLE if you are immediately going
to do another open() on it, because open() will close it for you.
(See open().) However, an explicit close on an input file resets
the line counter ($.), while the implicit close done by open()
does not.
If the file handle came from a piped open close will additionally
return FALSE if one of the other system calls involved fails or
if the program exits with non-zero status. (If the only problem
was that the program exited non-zero $! will be set to 0.) Also,
closing a pipe will wait for the process executing on the pipe to
complete, in case you want to look at the output of the pipe
afterwards. Closing a pipe explicitly also puts the exit status
value of the command into $?. Example:
open(OUTPUT, '|sort >foo') # pipe to sort
or die "Can't start sort: $!";
... # print stuff to output
close OUTPUT # wait for sort to finish
or warn $! ? "Error closing sort pipe: $!"
: "Exit status $? from sort";
open(INPUT, 'foo') # get sort's results
or die "Can't open 'foo' for input: $!";
FILEHANDLE may be an expression whose value gives the real
filehandle name.
closedir DIRHANDLE
Closes a directory opened by opendir().
connect SOCKET,NAME
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 packed address of the appropriate type for the
socket. See the examples in the section on Sockets:
Client/Server Communication in the perlipc manpage.
Page 11
PERLFUNC(1) PERLFUNC(1)
continue BLOCK
Actually a flow control statement rather than a function. If
there is a continue BLOCK attached to a BLOCK (typically in a
while or foreach), it is always executed just before the
conditional is about to be evaluated again, just like the third
part of a for loop in C. Thus it can be used to increment a loop
variable, even when the loop has been continued via the next
statement (which is similar to the C continue statement).
cos EXPR
Returns the cosine of EXPR (expressed in radians). If EXPR is
omitted takes cosine of $_.
For the inverse cosine operation, you may use the POSIX::acos()
function, or use this relation:
sub acos { atan2( sqrt(1 - $_[0] * $_[0]), $_[0] ) }
crypt PLAINTEXT,SALT
Encrypts a string exactly like the crypt(3) function in the C
library (assuming that you actually have a version there that has
not been extirpated as a potential munition). This can prove
useful for checking the password file for lousy passwords,
amongst other things. Only the guys wearing white hats should do
this.
Note that crypt is intended to be a one-way function, much like
breaking eggs to make an omelette. There is no (known)
corresponding decrypt function. As a result, this function isn't
all that useful for cryptography. (For that, see your nearby
CPAN mirror.)
Here's an example that makes sure that whoever runs this program
knows their own password:
$pwd = (getpwuid($<))[1];
$salt = substr($pwd, 0, 2);
system "stty -echo";
print "Password: ";
chop($word = <STDIN>);
print "\n";
system "stty echo";
if (crypt($word, $salt) ne $pwd) {
die "Sorry...\n";
} else {
print "ok\n";
}
Of course, typing in your own password to whoever asks you for it
Page 12
PERLFUNC(1) PERLFUNC(1)
is unwise.
dbmclose HASH
[This function has been superseded by the untie() function.]
Breaks the binding between a DBM file and a hash.
dbmopen HASH,DBNAME,MODE
[This function has been superseded by the tie() function.]
This binds a dbm(3), ndbm(3), sdbm(3), gdbm(), or Berkeley DB
file to a hash. HASH is the name of the hash. (Unlike normal
open, the first argument is NOT a filehandle, even though it
looks like one). DBNAME is the name of the database (without the
.dir or .pag extension if any). If the database does not exist,
it is created with protection specified by MODE (as modified by
the umask()). If your system supports only the older DBM
functions, you may perform only one dbmopen() in your program.
In older versions of Perl, if your system had neither DBM nor
ndbm, calling dbmopen() produced a fatal error; it now falls back
to sdbm(3).
If you don't have write access to the DBM file, you can only read
hash variables, not set them. If you want to test whether you
can write, either use file tests or try setting a dummy hash
entry inside an eval(), which will trap the error.
Note that functions such as keys() and values() may return huge
array values when used on large DBM files. You may prefer to use
the each() function to iterate over large DBM files. Example:
# print out history file offsets
dbmopen(%HIST,'/usr/lib/news/history',0666);
while (($key,$val) = each %HIST) {
print $key, ' = ', unpack('L',$val), "\n";
}
dbmclose(%HIST);
See also the AnyDBM_File manpage for a more general description
of the pros and cons of the various dbm approaches, as well as
the DB_File manpage for a particularly rich implementation.
defined EXPR
defined Returns a Boolean value telling whether EXPR has a value other
than the undefined value undef. If EXPR is not present, $_ will
be checked.
Many operations return undef to indicate failure, end of file,
system error, uninitialized variable, and other exceptional
conditions. This function allows you to distinguish undef from
other values. (A simple Boolean test will not distinguish among
Page 13
PERLFUNC(1) PERLFUNC(1)
undef, zero, the empty string, and "0", which are all equally
false.) Note that since undef is a valid scalar, its presence
doesn't necessarily indicate an exceptional condition: pop()
returns undef when its argument is an empty array, or when the
element to return happens to be undef.
You may also use defined() to check whether a subroutine exists.
On the other hand, use of defined() upon aggregates (hashes and
arrays) is not guaranteed to produce intuitive results, and
should probably be avoided.
When used on a hash element, it tells you whether the value is
defined, not whether the key exists in the hash. Use the exists
entry elsewhere in this document for the latter purpose.
Examples:
print if defined $switch{'D'};
print "$val\n" while defined($val = pop(@ary));
die "Can't readlink $sym: $!"
unless defined($value = readlink $sym);
sub foo { defined &$bar ? &$bar(@_) : die "No bar"; }
$debugging = 0 unless defined $debugging;
Note: Many folks tend to overuse defined(), and then are
surprised to discover that the number 0 and "" (the zero-length
string) are, in fact, defined values. For example, if you say
"ab" =~ /a(.*)b/;
the pattern match succeeds, and $1 is defined, despite the fact
that it matched "nothing". But it didn't really match nothing--
rather, it matched something that happened to be 0 characters
long. This is all very above-board and honest. When a function
returns an undefined value, it's an admission that it couldn't
give you an honest answer. So you should use defined() only when
you're questioning the integrity of what you're trying to do. At
other times, a simple comparison to 0 or "" is what you want.
Currently, using defined() on an entire array or hash reports
whether memory for that aggregate has ever been allocated. So an
array you set to the empty list appears undefined initially, and
one that once was full and that you then set to the empty list
still appears defined. You should instead use a simple test for
size:
if (@an_array) { print "has array elements\n" }
if (%a_hash) { print "has hash members\n" }
Using undef() on these, however, does clear their memory and then
report them as not defined anymore, but you shoudln't do that
unless you don't plan to use them again, because it saves time
Page 14
PERLFUNC(1) PERLFUNC(1)
when you load them up again to have memory already ready to be
filled.
This counterintuitive behaviour of defined() on aggregates may be
changed, fixed, or broken in a future release of Perl.
See also the undef, exists, and ref entries elsewhere in this
document .
delete EXPR
Deletes the specified key(s) and their associated values from a
hash. For each key, returns the deleted value associated with
that key, or the undefined value if there was no such key.
Deleting from $ENV{} modifies the environment. Deleting from a
hash tied to a DBM file deletes the entry from the DBM file.
(But deleting from a tie()d hash doesn't necessarily return
anything.)
The following deletes all the values of a hash:
foreach $key (keys %HASH) {
delete $HASH{$key};
}
And so does this:
delete @HASH{keys %HASH}
(But both of these are slower than the undef() command.) Note
that the EXPR can be arbitrarily complicated as long as the final
operation is a hash element lookup or hash slice:
delete $ref->[$x][$y]{$key};
delete @{$ref->[$x][$y]}{$key1, $key2, @morekeys};
die LIST
Outside of an eval(), prints the value of LIST to STDERR and
exits with the current value of $! (errno). If $! is 0, exits
with the value of ($? >> 8) (backtick `command` status). If ($?
>> 8) is 0, exits with 255. Inside an eval(), the error message
is stuffed into $@, and the eval() is terminated with the
undefined value; this makes die() the way to raise an exception.
Equivalent examples:
die "Can't cd to spool: $!\n" unless chdir '/usr/spool/news';
chdir '/usr/spool/news' or die "Can't cd to spool: $!\n"
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. Hint: sometimes appending ",
Page 15
PERLFUNC(1) PERLFUNC(1)
stopped" to your message will cause it to make better sense when
the string "at foo line 123" is appended. Suppose you are
running script "canasta".
die "/etc/games is no good";
die "/etc/games is no good, stopped";
produce, respectively
/etc/games is no good at canasta line 123.
/etc/games is no good, stopped at canasta line 123.
See also exit() and warn().
If LIST is empty and $@ already contains a value (typically from
a previous eval) that value is reused after appending
"\t...propagated". This is useful for propagating exceptions:
eval { ... };
die unless $@ =~ /Expected exception/;
If $@ is empty then the string "Died" is used.
You can arrange for a callback to be called just before the die()
does its deed, by setting the $SIG{__DIE__} hook. The associated
handler will be called with the error text and can change the
error message, if it sees fit, by calling die() again. See the
section on $SIG{expr} in the perlvar manpage for details on
setting %SIG entries, and the section on eval BLOCK for some
examples.
Note that the $SIG{__DIE__} hook is called even inside eval()ed
blocks/strings. If one wants the hook to do nothing in such
situations, put
die @_ if $^S;
as the first line of the handler (see the section on $^S in the
perlvar manpage).
do BLOCK
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.)
do SUBROUTINE(LIST)
A deprecated form of subroutine call. See the perlsub manpage.
Page 16
PERLFUNC(1) PERLFUNC(1)
do EXPR 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.
do 'stat.pl';
is just like
scalar eval `cat stat.pl`;
except that it's more efficient, more concise, keeps track of the
current filename for error messages, and searches all the -I
libraries if the file isn't in the current directory (see also
the @INC array in the section on Predefined Names in the perlvar
manpage). 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.
Note that inclusion of library modules is better done with the
use() and require() operators, which also do error checking and
raise an exception if there's a problem.
dump LABEL
This causes an immediate core dump. Primarily this is so that
you can use the undump program to turn your core dump into an
executable binary after having initialized all your variables at
the beginning of the program. When the new binary is executed it
will begin by executing a goto LABEL (with all the restrictions
that goto suffers). Think of it as a goto with an intervening
core dump and reincarnation. If LABEL is omitted, restarts the
program from the top. WARNING: any files opened at the time of
the dump will NOT be open any more when the program is
reincarnated, with possible resulting confusion on the part of
Perl. See also -u option in the perlrun manpage.
Example:
#!/usr/bin/perl
require 'getopt.pl';
require 'stat.pl';
%days = (
'Sun' => 1,
'Mon' => 2,
'Tue' => 3,
'Wed' => 4,
'Thu' => 5,
'Fri' => 6,
'Sat' => 7,
);
dump QUICKSTART if $ARGV[0] eq '-d';
Page 17
PERLFUNC(1) PERLFUNC(1)
QUICKSTART:
Getopt('f');
each HASH
When called in a list context, returns a 2-element array
consisting of the key and value for the next element of a hash,
so that you can iterate over it. When called in a scalar
context, returns the key for only the next element in the hash.
(Note: Keys may be "0" or "", which are logically false; you may
wish to avoid constructs like while ($k = each %foo) {} for this
reason.)
Entries are returned in an apparently random order. When the
hash is entirely read, a null array is returned in list context
(which when assigned produces a FALSE (0) value), and undef is
returned in a scalar context. The next call to each() after that
will start iterating again. There is a single iterator for each
hash, shared by all each(), keys(), and values() function calls
in the program; it can be reset by reading all the elements from
the hash, or by evaluating keys HASH or values HASH. 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.
The following prints out your environment like the printenv(1)
program, only in a different order:
while (($key,$value) = each %ENV) {
print "$key=$value\n";
}
See also keys() and values().
eof FILEHANDLE
eof ()
eof Returns 1 if the next read on FILEHANDLE will return end of file,
or if FILEHANDLE is not open. FILEHANDLE may be an expression
whose value gives the real filehandle name. (Note that this
function actually reads a character and then ungetc()s it, so it
is not very useful in an interactive context.) Do not read from
a terminal file (or call eof(FILEHANDLE) on it) after end-of-file
is reached. Filetypes such as terminals may lose the end-of-file
condition if you do.
An eof without an argument uses the last file read as argument.
Empty parentheses () may be used to indicate the pseudo file
formed of the files listed on the command line, i.e., eof() is
reasonable to use inside a while (<>) loop to detect the end of
only the last file. Use eof(ARGV) or eof without the parentheses
to test EACH file in a while (<>) loop. Examples:
Page 18
PERLFUNC(1) PERLFUNC(1)
# reset line numbering on each input file
while (<>) {
print "$.\t$_";
close(ARGV) if (eof); # Not eof().
}
# insert dashes just before last line of last file
while (<>) {
if (eof()) {
print "--------------\n";
close(ARGV); # close or break; is needed if we
# are reading from the terminal
}
print;
}
Practical hint: you almost never need to use eof in Perl, because
the input operators return undef when they run out of data.
eval EXPR
eval BLOCK
EXPR is parsed and executed as if it were a little Perl program.
It is executed in the context of the current Perl program, so
that any variable settings or subroutine and format definitions
remain afterwards. The value returned is the value of the last
expression evaluated, or a return statement may be used, just as
with subroutines. The last expression is evaluated in scalar or
array context, depending on the context of the eval.
If there is a syntax error or runtime error, or a die() statement
is executed, an undefined value is returned by eval(), and $@ is
set to the error message. If there was no error, $@ is
guaranteed to be a null string. If EXPR is omitted, evaluates
$_. The final semicolon, if any, may be omitted from the
expression. Beware that using eval() neither silences perl from
printing warnings to STDERR, nor does it stuff the text of
warning messages into $@. To do either of those, you have to use
the $SIG{__WARN__} facility. See warn() and the perlvar manpage.
Note that, because eval() traps otherwise-fatal errors, it is
useful for determining whether a particular feature (such as
socket() or symlink()) is implemented. It is also Perl's
exception trapping mechanism, where the die operator is used to
raise exceptions.
If the code to be executed doesn't vary, you may use the evalBLOCK
form to trap run-time errors without incurring the penalty
of recompiling each time. The error, if any, is still returned
in $@. Examples:
Page 19
PERLFUNC(1) PERLFUNC(1)
# make divide-by-zero nonfatal
eval { $answer = $a / $b; }; warn $@ if $@;
# same thing, but less efficient
eval '$answer = $a / $b'; warn $@ if $@;
# a compile-time error
eval { $answer = };
# a run-time error
eval '$answer ='; # sets $@
When using the eval{} form as an exception trap in libraries, you
may wish not to trigger any __DIE__ hooks that user code may have
installed. You can use the local $SIG{__DIE__} construct for
this purpose, as shown in this example:
# a very private exception trap for divide-by-zero
eval { local $SIG{'__DIE__'}; $answer = $a / $b; }; warn $@ if $@;
This is especially significant, given that __DIE__ hooks can call
die() again, which has the effect of changing their error
messages:
# __DIE__ hooks may modify error messages
{
local $SIG{'__DIE__'} = sub { (my $x = $_[0]) =~ s/foo/bar/g; die $x };
eval { die "foo foofs here" };
print $@ if $@; # prints "bar barfs here"
}
With an eval(), you should be especially careful to remember
what's being looked at when:
eval $x; # CASE 1
eval "$x"; # CASE 2
eval '$x'; # CASE 3
eval { $x }; # CASE 4
eval "\$$x++" # CASE 5
$$x++; # CASE 6
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 '$x', 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
WOULD like to use double quotes, except that in this particular
Page 20
PERLFUNC(1) PERLFUNC(1)
situation, you can just use symbolic references instead, as in
case 6.
exec LIST
The exec() function executes a system command AND NEVER RETURNS -
use system() instead of exec() if you want it to return. It fails
and returns FALSE only if the command does not exist and it is
executed directly instead of via your system's command shell (see
below).
If there is more than one argument in LIST, or if LIST is an
array with more than one value, calls execvp(3) with the
arguments in 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 /bin/sh -c 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 execvp(),
which is more efficient. Note: exec() and system() do not flush
your output buffer, so you may need to set $| to avoid lost
output. Examples:
exec '/bin/echo', 'Your arguments are: ', @ARGV;
exec "sort $outfile | uniq";
If you don't really want to execute the first argument, but want
to lie to the program you are executing about its own name, you
can specify the program you actually want to run as an "indirect
object" (without a comma) in front of the LIST. (This always
forces interpretation of the LIST as a multivalued list, even if
there is only a single scalar in the list.) Example:
$shell = '/bin/csh';
exec $shell '-sh'; # pretend it's a login shell
or, more directly,
exec {'/bin/csh'} '-sh'; # pretend it's a login shell
When the arguments get executed via the system shell, results
will be subject to its quirks and capabilities. See the section
on `STRING` in the perlop manpage for details.
exists EXPR
Returns TRUE if the specified hash key exists in its hash array,
even if the corresponding value is undefined.
print "Exists\n" if exists $array{$key};
print "Defined\n" if defined $array{$key};
print "True\n" if $array{$key};
A hash element can be TRUE only if it's defined, and defined if
Page 21
PERLFUNC(1) PERLFUNC(1)
it exists, but the reverse doesn't necessarily hold true.
Note that the EXPR can be arbitrarily complicated as long as the
final operation is a hash key lookup:
if (exists $ref->[$x][$y]{$key}) { ... }
exit EXPR
Evaluates EXPR and exits immediately with that value. (Actually,
it calls any defined END routines first, but the END routines may
not abort the exit. Likewise any object destructors that need to
be called are called before exit.) Example:
$ans = <STDIN>;
exit 0 if $ans =~ /^[Xx]/;
See also die(). If EXPR is omitted, exits with 0 status. The
only universally portable values for EXPR are 0 for success and 1
for error; all other values are subject to unpredictable
interpretation depending on the environment in which the Perl
program is running.
You shouldn't use exit() to abort a subroutine if there's any
chance that someone might want to trap whatever error happened.
Use die() instead, which can be trapped by an eval().
exp EXPR
exp Returns e (the natural logarithm base) to the power of EXPR. If
EXPR is omitted, gives exp($_).
fcntl FILEHANDLE,FUNCTION,SCALAR
Implements the fcntl(2) function. You'll probably have to say
use Fcntl;
first to get the correct function definitions. Argument
processing and value return works just like ioctl() below. Note
that fcntl() will produce a fatal error if used on a machine that
doesn't implement fcntl(2). For example:
use Fcntl;
fcntl($filehandle, F_GETLK, $packed_return_buffer);
fileno FILEHANDLE
Returns the file descriptor for a filehandle. This is useful for
constructing bitmaps for select(). If FILEHANDLE is an
expression, the value is taken as the name of the filehandle.
Page 22
PERLFUNC(1) PERLFUNC(1)
flock FILEHANDLE,OPERATION
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), fcntl(2)
locking, or lockf(3). flock() is Perl's portable file locking
interface, although it locks only entire files, not records.
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 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 added to LOCK_SH or LOCK_EX then
flock() will return immediately rather than blocking waiting for
the lock (check the return status to see if you got it).
To avoid the possibility of mis-coordination, Perl flushes
FILEHANDLE before (un)locking it.
Note that the emulation built with lockf(3) doesn't provide
shared locks, and it requires that FILEHANDLE be open with write
intent. These are the semantics that lockf(3) implements. Most
(all?) systems implement lockf(3) in terms of fcntl(2) locking,
though, so the differing semantics shouldn't bite too many
people.
Note also that some versions of flock() cannot lock things over
the network; you would need to use the more system-specific
fcntl() for that. If you like you can force Perl to ignore your
system's flock(2) function, and so provide its own fcntl(2)-based
emulation, by passing the switch -Ud_flock to the Configure
program when you configure perl.
Here's a mailbox appender for BSD systems.
use Fcntl ':flock'; # import LOCK_* constants
sub lock {
flock(MBOX,LOCK_EX);
# and, in case someone appended
# while we were waiting...
seek(MBOX, 0, 2);
}
sub unlock {
flock(MBOX,LOCK_UN);
}
open(MBOX, ">>/usr/spool/mail/$ENV{'USER'}")
or die "Can't open mailbox: $!";
Page 23
PERLFUNC(1) PERLFUNC(1)
lock();
print MBOX $msg,"\n\n";
unlock();
See also the DB_File manpage for other flock() examples.
fork Does a fork(2) system call. Returns the child pid to the parent
process and 0 to the child process, or undef if the fork is
unsuccessful. Note: unflushed buffers remain unflushed in both
processes, which means you may need to set $| ($AUTOFLUSH in
English) or call the autoflush() method of IO::Handle to avoid
duplicate output.
If you fork() without ever waiting on your children, you will
accumulate zombies:
$SIG{CHLD} = sub { wait };
There's also the double-fork trick (error checking on fork()
returns omitted);
unless ($pid = fork) {
unless (fork) {
exec "what you really wanna do";
die "no exec";
# ... or ...
## (some_perl_code_here)
exit 0;
}
exit 0;
}
waitpid($pid,0);
See also the perlipc manpage for more examples of forking and
reaping moribund children.
Note that if your forked child inherits system file descriptors
like STDIN and STDOUT that are actually connected by a pipe or
socket, even if you exit, the remote server (such as, say, httpd
or rsh) won't think you're done. You should reopen those to
/dev/null if it's any issue.
format Declare a picture format with use by the write() function. For
example:
format Something =
Test: @<<<<<<<< @||||| @>>>>>
$str, $%, '$' . int($num)
.
Page 24
PERLFUNC(1) PERLFUNC(1)
$str = "widget";
$num = $cost/$quantity;
$~ = 'Something';
write;
See the perlform manpage for many details and examples.
formline PICTURE,LIST
This is an internal function used by formats, though you may call
it too. It formats (see the perlform manpage) a list of values
according to the contents of PICTURE, placing the output into the
format output accumulator, $^A (or $ACCUMULATOR in English).
Eventually, when a write() is done, the contents of $^A are
written to some filehandle, but you could also read $^A yourself
and then set $^A back to "". Note that a format typically does
one formline() per line of form, but the formline() function
itself doesn't care how many newlines are embedded in the
PICTURE. This means that the ~ and ~~ 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.
Be careful if you put double quotes around the picture, because
an "@" character may be taken to mean the beginning of an array
name. formline() always returns TRUE. See the perlform manpage
for other examples.
getc FILEHANDLE
getc Returns the next character from the input file attached to
FILEHANDLE, or a null string at end of file. If FILEHANDLE is
omitted, reads from STDIN. This is not particularly efficient.
It cannot be used to get unbuffered single-characters, however.
For that, try something more like:
if ($BSD_STYLE) {
system "stty cbreak </dev/tty >/dev/tty 2>&1";
}
else {
system "stty", '-icanon', 'eol', "\001";
}
$key = getc(STDIN);
if ($BSD_STYLE) {
system "stty -cbreak </dev/tty >/dev/tty 2>&1";
}
else {
system "stty", 'icanon', 'eol', '^@'; # ASCII null
}
print "\n";
Page 25
PERLFUNC(1) PERLFUNC(1)
Determination of whether $BSD_STYLE should be set is left as an
exercise to the reader.
The POSIX::getattr() function can do this more portably on
systems alleging POSIX compliance. See also the Term::ReadKey
module from your nearest CPAN site; details on CPAN can be found
on the CPAN entry in the perlmod manpage.
getlogin
Returns the current login from /etc/utmp, if any. If null, use
getpwuid().
$login = getlogin || getpwuid($<) || "Kilroy";
Do not consider getlogin() for authentication: it is not as
secure as getpwuid().
getpeername SOCKET
Returns the packed sockaddr address of other end of the SOCKET
connection.
use Socket;
$hersockaddr = getpeername(SOCK);
($port, $iaddr) = unpack_sockaddr_in($hersockaddr);
$herhostname = gethostbyaddr($iaddr, AF_INET);
$herstraddr = inet_ntoa($iaddr);
getpgrp PID
Returns the current process group for the specified PID. Use a
PID of 0 to get the current process group for the current
process. Will raise an exception if used on a machine that
doesn't implement getpgrp(2). If PID is omitted, returns process
group of current process. Note that the POSIX version of
getpgrp() does not accept a PID argument, so only PID==0 is truly
portable.
getppid Returns the process id of the parent process.
getpriority WHICH,WHO
Returns the current priority for a process, a process group, or a
user. (See the getpriority(2) manpage.) Will raise a fatal
exception if used on a machine that doesn't implement
getpriority(2).
getpwnam NAME
getgrnam NAME
gethostbyname NAME
Page 26
PERLFUNC(1) PERLFUNC(1)
getnetbyname NAME
getprotobyname NAME
getpwuid UID
getgrgid GID
getservbyname NAME,PROTO
gethostbyaddr ADDR,ADDRTYPE
getnetbyaddr ADDR,ADDRTYPE
getprotobynumber NUMBER
getservbyport PORT,PROTO
getpwent
getgrent
gethostent
getnetent
getprotoent
getservent
setpwent
setgrent
sethostent STAYOPEN
setnetent STAYOPEN
setprotoent STAYOPEN
setservent STAYOPEN
endpwent
endgrent
endhostent
endnetent
Page 27
PERLFUNC(1) PERLFUNC(1)
endprotoent
endservent
These routines perform the same functions as their counterparts
in the system library. Within a list context, the return values
from the various get routines are as follows:
($name,$passwd,$uid,$gid,
$quota,$comment,$gcos,$dir,$shell) = getpw*
($name,$passwd,$gid,$members) = getgr*
($name,$aliases,$addrtype,$length,@addrs) = gethost*
($name,$aliases,$addrtype,$net) = getnet*
($name,$aliases,$proto) = getproto*
($name,$aliases,$port,$proto) = getserv*
(If the entry doesn't exist you get a null list.)
Within a scalar context, you get the name, unless the function
was a lookup by name, in which case you get the other thing,
whatever it is. (If the entry doesn't exist you get the
undefined value.) For example:
$uid = getpwnam
$name = getpwuid
$name = getpwent
$gid = getgrnam
$name = getgrgid
$name = getgrent
etc.
The $members value returned by getgr*() is a space separated list
of the login names of the members of the group.
For the gethost*() functions, if the h_errno variable is
supported in C, it will be returned to you via $? if the function
call fails. The @addrs value returned by a successful call is a
list of the raw addresses returned by the corresponding system
library call. In the Internet domain, each address is four bytes
long and you can unpack it by saying something like:
($a,$b,$c,$d) = unpack('C4',$addr[0]);
getsockname SOCKET
Returns the packed sockaddr address of this end of the SOCKET
connection.
use Socket;
$mysockaddr = getsockname(SOCK);
($port, $myaddr) = unpack_sockaddr_in($mysockaddr);
Page 28
PERLFUNC(1) PERLFUNC(1)
getsockopt SOCKET,LEVEL,OPTNAME
Returns the socket option requested, or undefined if there is an
error.
glob EXPR
glob Returns the value of EXPR with filename expansions such as a
shell would do. This is the internal function implementing the
<*.c> operator, but you can use it directly. If EXPR is omitted,
$_ is used. The <*.c> operator is discussed in more detail in
the section on I/O Operators in the perlop manpage.
gmtime EXPR
Converts a time as returned by the time function to a 9-element
array with the time localized for the standard Greenwich time
zone. Typically used as follows:
# 0 1 2 3 4 5 6 7 8
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
gmtime(time);
All array elements are numeric, and come straight out of a struct
tm. In particular this means that $mon has the range 0..11 and
$wday has the range 0..6 with sunday as day 0. Also, $year is
the number of years since 1900, not simply the last two digits of
the year.
If EXPR is omitted, does gmtime(time()).
In a scalar context, returns the ctime(3) value:
$now_string = gmtime; # e.g., "Thu Oct 13 04:54:34 1994"
Also see the timegm() function provided by
|