accept |
accept newsocket, genericsocket |
alarm |
alarm n |
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 return value is the number of seconds remaining on the previous timer.
atan2 |
atan2 y, x |
$pi = atan2(1,1) * 4;
For the tangent operation, you may use the POSIX::tan( ) function, or use the familiar relation:
sub tan { sin($_[0]) / cos($_[0]) }
bind |
bind socket, address |
binmode |
binmode filehandle |
binmode has no effect under Unix, Plan9, or other systems that use a single \n (newline) character as a line delimiter. On systems such as Win32 or MS-DOS, binmode is needed to prevent the translation of the line delimiter characters to and from \n.
bless |
bless $ref, [classname] |
caller |
caller [n] |
($package, $filename, $line) = caller;
With an argument it evaluates n as the number of stack frames to go back before the current one. It also reports some additional information that the debugger uses to print a stack trace:
$i = 0; while (($pack, $file, $line, $subname, $hasargs, $wantarray, $evaltext, $is_require) = caller($i++)) { ... }
Furthermore, when called from within the DB package, caller returns more detailed information: it sets the list variable @DB::args as the argument passed in the given stack frame.
chdir |
chdir dirname |
chmod |
chmod mode, filelist |
$cnt = chmod 0755, 'file1', 'file2';
will set $cnt to 0, 1, or 2, depending on how many files got changed (in the sense that the operation succeeded, not in the sense that the bits were different afterward).
chomp |
chomp $var chomp @list |
chop |
chop $var chop @list |
chown |
chown uid, gid, files |
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 |
chr number |
chroot |
chroot dirname |
close |
close filehandle |
filehandle may be an expression with a value that gives a real filehandle name. It may also be a reference to a filehandle object returned by some of the object-oriented I/O packages.
closedir |
closedir dirhandle |
connect |
connect socket, address |
To disconnect a socket, use either close or shutdown.
cos |
cos num |
sub acos { atan2( sqrt(1 - $_[0] * $_[0]), $_[0] ) }
crypt |
crypt string, salt |
if (crypt ($guess, $pass) eq $pass) { # guess is correct }
The variable $pass is the password string from the password file. crypt merely uses the first two characters from this string for the saltargument.
dbmclose |
dbmclose %hash |
This function is actually just a call to untie with the proper arguments, but is provided for backward compatibility with older versions of Perl.
dbmopen |
dbmopen %hash, dbname, mode |
Values assigned to the hash prior to the dbmopen are not accessible. If you don't have write access to the DBM file, you can only read the hash variables, not set them.
This function is actually just a call to tie with the proper arguments, but is provided for backward compatibility with older versions of Perl.
defined |
defined expr |
A scalar that contains no valid string, numeric, or reference value is known as the undefined value, or undef. Many operations return the undefined value under exceptional conditions, such as end-of-file, uninitialized variable, system error, and so on. This function allows you to distinguish between an undefined null string and a defined null string when you're using operators that might return a real null string.
You can use defined to see if a subroutine exists, that is, if the subroutine definition has been successfully parsed. However, using defined on an array or a hash is not guaranteed to produce intuitive results and should be avoided.
delete |
delete $hash{key} delete @hash{@keys} |
For normal hashes, the delete function returns the value (not the key) that was deleted, but this behavior is not guaranteed for tied hashes, such as those bound to DBM files. To test whether a hash element has been deleted, use exists.
die |
die message |
die exits the programs with the current value of the $! variable, which contains the text describing the most recent operating system error value. This value can be used in the message to describe what the problem may have been.
die behaves differently inside an eval statement. It places the error message in the $@ variable and aborts the eval, which returns an undefined value. This use of die can raise runtime exceptions that can be caught at a higher level of the program.
do |
do {block} |
dump |
dump label |
As of Perl 5.8, dump is now largely obsolete, partly because it's difficult to convert a core file into an executable, and because the real compiler backends for generating portable bytecode and compilable C code have superseded it. That's why you should now invoke it as "CORE::dump( )" if you don't want to be warned against a possible typo.
The undump program is not available on all systems and may not be compatible with specific ports of Perl.
each |
each %hash |
There is a single iterator for each hash, shared by all each, keys, and values function calls in the program. This means that after a keys or values call, the next each call will start again from the beginning.
endgrent |
endgrent |
endhostent |
endhostent |
endnetent |
endnetent |
endprotoent |
endprotoent |
endpwent |
endpwent |
endservent |
endservent |
eof |
eof filehandle eof( ) |
while (<>) { if (eof( )) { print "-" x 30, "\n"; } print; }
eval |
eval string eval {block} |
With eval string, the contents of string are compiled and executed at runtime. For example:
$a = 3, $b = 4; $c = '$a * $b'; print (eval "$c"); # Prints 12
The string form of eval is useful for executing strings produced at runtime from standard or other dynamic input sources. If the string produces an error, either from syntax or at runtime, the eval exits with the undefined value and places the error in $@. If string is omitted, the operator evaluates $_.
The block form of eval is used in Perl programs to handle runtime errors (exceptions). The code in block is compiled only once during the compilation of the main program. If there is a syntax error in the block, it will produce an error at compile time. If the code in block produces a runtime error (or if a die statement is encountered), the eval exits, and the error is placed in $@. For example, the following code can be used to trap a divide-by-zero error at runtime:
eval { $a = 10; $b = 0; $c = $a / $b; # Causes runtime error # Trapped by eval }; print $@; # Prints "Illegal division by 0 at # try.pl line 3"
As with any code in a block, a final semicolon is not required.
exec |
exec command |
command may be a scalar containing a string with the name of the program to run and any arguments. This string is checked for shell metacharacters, and if there are any, passes the string to /bin/sh/ -c for parsing. Otherwise, the string is read as a program command, bypassing any shell processing. The first word of the string is used as the program name, with any remaining words used as arguments.
command may also be a list value in which the first element is parsed as the program name and remaining elements as arguments. For example:
exec 'echo', 'Your arguments are: ', @ARGV;
The exec function is not implemented for Perl on Win32 platforms.
exists |
exists $hash{$key} |
exit |
exit status |
$ans = <STDIN>; exit 0 if $ans =~ /^[Xx]/;
If status is omitted, the function exits with 0. 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 |
exp num |
fcntl |
fcntl filehandle, function, arg |
use Fcntl;
This module imports the correct functiondefinitions. See the description of the Fcntl module in Chapter 8, "Standard Modules".
The return value of fcntl (and ioctl) is as follows:
System call returns |
Perl returns |
---|---|
-1 |
Undefined value |
0 |
String "0 but true" |
Anything else |
That number |
Thus Perl returns true on success and false on failure, yet you can still easily determine the actual value returned by the operating system.
fileno |
fileno filehandle |
flock |
flock filehandle, operation |
operation is the type of locking function to perform. The number by each operation name is the argument that Perl's flock takes by default. You may also use the operation names if you explicitly import them from the Fcntl module with use Fcntl ":flock".
fork |
fork |
formline |
formline picture, variables |
Be careful if you put double quotes around the picture, since an @ character may be taken to mean the beginning of an array name. formline always returns true. See Chapter 4, "The Perl Language" for more information.
getc |
getc filehandle |
getgrent |
getgrent |
($name, $passwd, $gid, $members)
in which $members contains a space-separated list of the login names of the members of the group. In scalar context, getgrent returns only the group name.
getgrgid |
getgrgid gid |
($name, $passwd, $gid, $members)
in which $members contains a space-separated list of the login names of the members of the group. If you want to do this repeatedly, consider caching the data in a hash using getgrent. In scalar context, getgrgid returns only the group name.
getgrnam |
getgrnam name |
($name, $passwd, $gid, $members)
in which $members contains a space-separated list of the login names of the members of the group. In scalar context, getgrnam returns only the numeric group ID.
gethostbyaddr |
gethostbyaddr address, [addrtype] |
($name, $aliases, $addrtype, $length, @addrs)
in which @addrs is a list of packed binary addresses. In the Internet domain, each address is four bytes long and can be unpacked by something like:
($a, $b, $c, $d) = unpack('C4', $addrs[0]);
In scalar context, gethostbyaddr returns only the hostname.
gethostbyname |
gethostbyname name |
($name, $aliases, $addrtype, $length, @addrs)
in which @addrs is a list of raw addresses. In scalar context, gethostbyname returns only the host address.
gethostent |
gethostent |
($name, $aliases, $addrtype, $length, @addrs)
in which @addrs is a list of raw addresses. Scripts that use this function should not be considered portable.
getlogin |
getlogin |
$login = getlogin || getpwuid($<) || "Intruder!!";
getnetbyaddr |
getnetbyaddr address, [addrtype] |
($name, $aliases, $addrtype, $net)
In scalar context, getnetbyaddr returns only the network name.
getnetbyname |
getnetbyname name |
($name, $aliases, $addrtype, $net)
In scalar context, getnetbyname returns only the network address.
getnetent |
getnetent |
($name, $aliases, $addrtype, $net)
In scalar context, getnetent returns only the network name.
getpeername |
getpeername socket |
use Socket; $hersockaddr = getpeername SOCK; ($port, $heraddr) = unpack_sockaddr_in($hersockaddr); $herhostname = gethostbyaddr($heraddr, AF_INET); $herstraddr = inet_ntoa($heraddr);
getpgrp |
getpgrp pid |
getppid |
getppid |
getpriority |
getpriority type, id |
The priority will be an integer value. Lower values indicate higher priority (negative values may be returned on some systems). Invoking getpriority will produce a fatal error if used on a machine that doesn't implement the getpriority system call.
getprotobyname |
getprotobyname name |
($name, $aliases, $protocol_number)
In scalar context, getprotobyname returns only the protocol number.
getprotobynumber |
getprotobynumber number |
($name, $aliases, $protocol_number)
In scalar context, getprotobynumber returns only the protocol name.
getprotoent |
getprotoent |
($name, $aliases, $protocol_number)
In scalar context, getprotoent returns only the protocol name.
getpwent |
getpwent |
($name,$passwd,$uid,$gid,$quota,$comment,$gcos,$dir,$shell)
Some machines may use the quota and comment fields for other purposes, but the remaining fields will always be the same. To set up a hash for translating login names to uids, do this:
while (($name, $passwd, $uid) = getpwent) { $uid{$name} = $uid; }
In scalar context, getpwent returns only the username.
getpwnam |
getpwnam name |
($name,$passwd,$uid,$gid,$quota,$comment,$gcos,$dir,$shell)
If you want to do this repeatedly, consider caching the data in a hash using getpwent.
In scalar context, getpwnam returns only the numeric user ID.
getpwuid |
getpwuid uid |
($name,$passwd,$uid,$gid,$quota,$comment,$gcos,$dir,$shell)
If you want to do this repeatedly, consider slurping the data into a hash using getpwent.
In scalar context, getpwuid returns the username.
getservbyname |
getservbyname name, proto |
($name, $aliases, $port_number, $protocol_name)
In scalar context, getservbyname returns only the service port number.
getservbyport |
getservbyport port, proto |
($name, $aliases, $port_number, $protocol_name)
In scalar context, getservbyport returns only the service port name.
getservent |
getservent |
($name, $aliases, $port_number, $protocol_name)
In scalar context, getservent returns only the service port name.
getsockname |
getsockname socket |
getsockopt |
getsockopt socket, level, optname |
glob |
glob expr |
The glob function is not related to the Perl notion of typeglobs, other than that they both use a * to represent multiple items.
gmtime |
gmtime expr |
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time);
All list elements are numeric and come straight out of a C language struct tm. In particular, this means that $mon has the range 0..11, $wday has the range 0..6, and the year has had 1,900 subtracted from it. (You can remember which elements are 0-based because you're always using these as subscripts into 0-based arrays containing month and day names.) If expr is omitted, it does gmtime(time). For example, to print the current month in London:
$london_month = (qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec))[(gmtime)[4]];
The Perl library module Time::Local contains a subroutine, timegm( ), that can convert in the opposite direction.
In scalar context, gmtime returns a ctime(3)-like string based on the GMT time value.
goto |
goto label goto &name |
goto &name substitutes a call to the named subroutine for the currently running subroutine. This is used by AUTOLOAD subroutines that wish to load another subroutine and pretend that this subroutine—and not the original one—had been called in the first place (except that any modifications to @_ in the original subroutine are propagated to the replacement subroutine). After the goto, not even caller will be able to tell that the original routine was called first.
grep |
grep expr, list grep {block} list |
For example, presuming @all_lines contains lines of code, this example weeds out comment lines:
@code_lines = grep !/^#/, @all_lines;
hex |
hex hexnum |
$number = hex("ffff12c0");
To do the inverse function, use:
sprintf "%lx", $number; # That's a letter 'l', not a one
index |
index string, substr, [start] |
ioctl |
ioctl filehandle, function, arg |
join |
join char, list |
$_ = join ':', $login,$passwd,$uid,$gid,$gcos,$home,$shell;
To do the opposite, see split. To join things together into fixed-position fields, see pack.
keys |
keys %hash |
In scalar context, keys returns the number of elements of the hash (and resets the each iterator).
keys can be used as an lvalue to increase the number of hash buckets allocated for the hash:
keys %hash = 200;
kill |
kill sig, processes |
last |
last label |
lc |
lc string |
lcfirst |
lcfirst string |
length |
length val |
Do not try to use length to find the size of an array or hash. Use scalar @array for the size of an array, and scalar keys %hashfor the size of a hash.
link |
link oldfile, newfile |
listen |
listen socket, queuesize |
local |
local vars |
Subroutines called within the scope of a local variable will see the localized inner value of the variable. The technical term for this process is "dynamic scoping." Use my for true private variables.
localtime |
localtime val |
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
All list elements are numeric. The element $mon (month) has the range 0..11, and $wday (weekday) has the range 0..6. The year has had 1,900 subtracted from it. (You can remember which elements are 0-based because you're always using them as subscripts into 0-based arrays containing month and day names.) If val is omitted, it does localtime(time). For example, to get the name of the current day of the week:
$thisday = (Sun,Mon,Tue,Wed,Thu,Fri,Sat)[(localtime)[6]];
The Perl library module Time::Local contains a subroutine, timelocal( ), that can convert in the opposite direction.
In scalar context, localtime returns a ctime(3)-like string based on the localtime value.
lstat |
lstat file |
map |
map {block} list map expr, list |
@words = map { split ' ' } @lines;
splits a list of lines into a list of words. Often, though, there is a one-to-one mapping between input values and output values:
@chars = map chr, @nums;
This statement translates a list of numbers to the corresponding characters.
mkdir |
mkdir filename, mode |
msgctl |
msgctl id, cmd, arg |
require "ipc.ph"; require "msg.ph";
This function is available only on machines supporting System V IPC.
msgget |
msgget key, flags |
require "ipc.ph"; require "msg.ph";
This function is available only on machines supporting System V IPC.
msgrcv |
msgrcv id, var, size, type, flags |
require "ipc.ph"; require "msg.ph";
This function is available only on machines supporting System V IPC.
msgsnd |
msgsnd id, msg, flags |
$msg = pack "L a*", $type, $text_of_message;
The function returns true if successful, or false if there is an error. On error, it puts the error code into $!. Before calling, you should say:
require "ipc.ph"; require "msg.ph";
This function is available only on machines supporting System V IPC.
my |
my vars |
Unlike local, this operator has nothing to do with global variables, other than hiding any other variable of the same name from view within its scope. (A global variable can always be accessed through its package-qualified form or a symbolic reference, however.) A private variable is not visible until the statement after its declaration. Subroutines called from within the scope of such a private variable cannot see the private variable unless the subroutine is also textually declared within the scope of the variable.
next |
next label |
no |
no Module list |
no strict 'refs'
allows soft references to the end of the block scope if:
use strict 'refs'
was previously invoked.
oct |
oct ostring |
$val = oct $val if $val =~ /^0/;
If ostring is omitted, the function interprets $_. To perform the inverse function on octal numbers, use:
$oct_string = sprintf "%lo", $number;
open |
open filehandle, filename open filehandle, mode, filename open filehandle, mode, expr, list (new in 5.8) open filehandle, mode, reference (new in 5.8) |
If filename is preceded by either < or nothing, the file is opened for input (read-only). If filename is preceded by >, the file is opened for output. If the file doesn't exist, it will be created; if the file exists, it will be overwritten with output using >. Preceding the filename with >> opens an output file for appending. For both read and write access, use a + before < or >.
If you choose to use the three-or-more-arguments form of open, you can use separate mode and filename arguments, such as open($fh, $mode, $filename), in which $moderepresents an open mode or pipe. For example:
my $mode = '+<'; my $filename = 'whatever.txt'; open(FH, $mode, $filename) or die("can't open $filename: $!");
As covered in Chapter 4, "The Perl Language", you can build Perl 5.8 and newer with PerlIO support, which offers additional features for your system's I/O (STDIO). This allows you to do neat things, such as specify utf-8 as your default encoding for all of your I/O, or set your default line endings with 'crlf'. In addition, you can select piping to or extracting information from an external program with '|-' and '-|', respectively. For example:
my $prog = "webster overworked"; open($fh, '-|', $prog) or die("can't open pipe to '$prog': $!");
or, similarly:
my @prog_info = qw(/usr/contrib/bin/webster overworked); open($fh, '-|', @prog_info) or die(...);
A filehandle may also be attached to a process by using a piped command. If the filename begins with |, the filename is interpreted as a command to which output is to be piped. If the filename ends with a |, the filename is interpreted as a command that pipes input to you. You may not have an open command that pipes both in and out.
Any pipe command containing shell metacharacters is passed to the shell for execution; otherwise, it is executed directly by Perl. The filename - refers to STDIN, and > refers to STDOUT. open returns nonzero upon success, the undefined value otherwise. If the open involved a pipe, the return value happens to be the process ID of the subprocess.
opendir |
opendir dirhandle, directory |
ord |
ord expr |
our |
our vars |
package Foo; our $bar; # Declares $Foo::bar for rest of lexical scope $bar = 20; package Bar; print $bar; # Prints 20
You my use multiple our declarations in the same lexical scope if they are in different packages. If they are in the same package, Perl will emit warnings if you have asked for them:
use warnings; package Foo; our $bar; # Declares $Foo::bar for rest of lexical scope $bar = 20; package Bar; our $bar = 30; # Declares $Bar::bar for rest of lexical scope print $bar; # Prints 30 our $bar; # Emits warning
pack |
pack template, list |
Character |
Meaning |
---|---|
@ |
Null-fill to absolute position. |
( |
Start of a ( ) group. |
a |
An ASCII string, will be null padded. |
A |
An ASCII string, will be space padded. |
b |
A bit string, low-to-high order (such as vec( )). |
B |
A bit string, high-to-low order. |
c |
A signed char value. |
C |
An unsigned char value. |
d |
A double-precision float in the native format. |
D |
A long double-precision float in the native format. Long doubles are avai able only if your system supports long double values and if Perl has been compiled to support these values. Causes a fatal error otherwise. New in 5.8. |
f |
A single-precision float in the native format. |
F |
A floating-point value in the native format, i.e., a Perl internal floating-point value (NV). New in 5.8. |
h |
A hexadecimal string, low nybble first. |
H |
A hexadecimal string, high nybble first. |
i |
A signed integer value. |
I |
An unsigned integer value. |
l |
A signed long value. |
j |
A signed integer value, i.e., a Perl internal integer (IV). New in 5.8. |
J |
An unsigned integer value, i.e., a Perl internal unsigned integer (UV). New in 5.8. |
L |
An unsigned long value. |
n |
A short in "network" (big-endian) order. |
N |
A long in "network" (big-endian) order. |
p |
A pointer to a string. |
P |
A pointer to a structure (fixed-length string). |
q |
A signed quad (64-bit) value. New in 5.8. |
Q |
An unsigned quad value. Quads are available only if your system supports 64-bit integer values and if Perl has been compiled to support these values. Causes a fatal error otherwise. New in 5.8. |
s |
A signed short value. |
S |
An unsigned short value. |
v |
A short in "VAX" (little-endian) order. |
V |
A long in "VAX" (little-endian) order. |
u |
A uuencoded string. |
U |
A Unicode character number. Encodes to UTF-8 internally (or UTF-EBCDIC in EBCDIC platforms). New in 5.8. |
w |
A BER compressed integer. |
x |
A null byte. |
X |
Back up a byte. |
Z |
A null terminated (ASCII) string. Will be null padded. New in 5.8. |
Generally, the same template may also be used in the unpack function. If you want to join variable length fields with a delimiter, use the join function.
package |
package namespace |
Using package without an argument is possible, but since its semantics are unclear, package; has been depracated in Perl 5.8. If you intend to disallow variables that aren't fully qualified, use strict; instead.
Typically, you put a package declaration as the first thing in a file that will be included by the require or use operator, but you can put one anywhere that a statement would be legal. When defining a class or a module file, it is customary to name the package the same name as the file, to avoid confusion. (It's also customary to name such packages beginning with a capital letter, because lowercase modules are, by convention, interpreted as pragmas.)
pipe |
pipe readhandle, writehandle |
pop |
pop @array |
If there are no elements in the array, pop returns the undefined value. See also push and shift. If you want to pop more than one element, use splice.
pos |
pos $scalar |
$grafitto = "fee fie foe foo"; while ($grafitto =~ m/e/g) { print pos $grafitto, "\n"; }
prints 2, 3, 7, and 11, the offsets of each of the characters following an "e". The pos function may be assigned a value to tell the next m//g where to start.
print [filehandle] list |
print { $OK ? "STDOUT" : "STDERR" } "stuff\n"; print { $iohandle[$i] } "stuff\n";
If list is also omitted, $_ is printed. Note that because print takes a list, anything in the list is evaluated in list context.
printf |
printf [filehandle] format, list |
print filehandle sprintf(format, list);
printf and sprintf use the same format syntax, but sprintf returns only a string; it doesn't print to a filehandle. The format string contains text with embedded field specifiers into which the elements of list are substituted in order, one per field. Field specifiers follow the form:
%m.nx
A percent sign begins each field, and x is the type of field. The optional m gives the minimum field width for appropriate field types (negative m left-justifies). The .n gives the precision for a specific field type, such as the number of digits after a decimal point for floating-point numbers, the maximum length for a string, and the minimum length for an integer.
Field specifiers (x) may be the following:
Code |
Meaning |
---|---|
% |
Percent sign |
c |
Character |
d |
Decimal integer |
e |
Exponential format floating-point number |
E |
Exponential format floating-point number with uppercase E |
f |
Fixed-point format floating-point number |
g |
Floating-point number, in either exponential or fixed decimal notation |
G |
Like g with uppercase E (if applicable) |
ld |
Long decimal integer |
lo |
Long octal integer |
lu |
Long unsigned decimal integer |
lx |
Long hexadecimal integer |
o |
Octal integer |
s |
String |
u |
Unsigned decimal integer |
x |
Hexadecimal integer |
X |
Hexadecimal integer with uppercase letters |
p |
The Perl value's address in hexadecimal |
n |
Special value that stores the number of characters output so far into the next variable in the parameter list |
prototype |
prototype function |
push |
push @array, list |
q/string/ |
q/string/ qq/string/ qx/string/ qw/strings/ |
quotemeta |
quotemeta expr |
rand |
rand num |
To get an integral value, combine this with int, as in:
$roll = int(rand 6) + 1; # $roll is now an integer between 1 and 6
read |
read filehandle, $var, length, [offset] |
To copy data from the filehandle FROM into the filehandle TO, you could say:
while (read FROM, $buf, 16384) { print TO $buf; }
Note that the opposite of read is simply print, which already knows the length of the string you want to write and can write a string of any length.
Perl's read function is actually implemented in terms of standard I/O's fread function, so the actual read system call may read more than length bytes to fill the input buffer, and fread may do more than one system read to fill the buffer. To gain greater control, specify the real system call using sysread.
readdir |
readdir dirhandle |
readline |
readline *filehandle |
readlink |
readlink name |
readpipe |
readpipe cmd |
recv |
recv socket, $var, len, flags |
redo |
redo [label] |
ref |
ref $var |
REF SCALAR ARRAY HASH CODE GLOB
If the referenced object has been blessed into a package, that package name is returned instead. You can think of ref as a "typeof" operator.
rename |
rename oldname, newname |
require |
require filename require num require package |
If the argument is a string filename, this function includes and executes the Perl code found in the separate file of that name. This is similar to performing an eval on the contents of the file, except that require checks to see that the library file has not been included already. The function also knows how to search the include path stored in the @INC array.
If requires argument is a number num, the version number of the currently executing Perl binary (as known by $]) is compared to num. If it is smaller, execution is immediately aborted. Thus, a script that requires Perl version 5.003 can have as its first line:
require 5.003;
and earlier versions of Perl will abort.
If require's argument is a package name, require assumes an automatic .pm suffix, making it easy to load standard modules. This is like use, except that it happens at runtime, not compile time, and the import routine is not called.
reset |
reset expr |
Lexical variables (created by my) are not affected. Use of reset is vaguely deprecated.
return |
return expr |
The supplied expression will be evaluated in the context of the subroutine invocation. That is, if the subroutine was called in a scalar context, expr is also evaluated in scalar context. If the subroutine was invoked in a list context, then expr is also evaluated in list context and can return a list value. A return with no argument returns the undefined value in scalar context and a null list in list context. The context of the subroutine call can be determined from within the subroutine by using the (misnamed) wantarray function.
reverse |
reverse list |
rewinddir |
rewinddir dirhandle |
rindex |
rindex str, substr, [position] |
rmdir |
rmdir name |
seek |
seek filehandle, offset, whence |
seekdir |
seekdir dirhandle, pos |
select |
select filehandle |
select |
select rbits, wbits, ebits, timeout |
$rbits = $wbits = $ebits = ""; vec($rbits, fileno(STDIN), 1) = 1; vec($wbits, fileno(STDOUT), 1) = 1; $ein = $rin | $win;
The select call blocks until one or more file descriptors is ready for reading, writing, or reporting an error condition. timeout is given in seconds and tells select how long to wait.
semctl |
semctl id, semnum, cmd, arg |
require "ipc.ph"; require "sem.ph";
This function is available only on machines supporting System V IPC.
semget |
semget key, nsems, size, flags |
require "ipc.ph"; require "sem.ph";
This function is available only on machines supporting System V IPC.
semop |
semop key, opstring |
require "ipc.ph"; require "sem.ph";
This function is available only on machines supporting System V IPC.
send |
send socket, msg, flags, [dest] |
Some non-Unix systems improperly treat sockets as different objects than ordinary file descriptors, which means that you must always use send and recv on sockets rather than the standard I/O operators.
sethostent |
sethostent stayopen |
setgrent |
setgrent |
setnetent |
setnetent stayopen |
setpgrp |
setpgrp pid, pgrp |
setpriority |
setpriority which, who, priority |
setprotoent |
setprotoent stayopen |
setpwent |
setpwent |
setservent |
setservent stayopen |
setsockopt |
setsockopt socket, level, optname, optval |
shift |
shift @array |
shmctl |
shmctl id, cmd, arg |
require "ipc.ph"; require "shm.ph";
This function is available only on machines supporting System V IPC.
shmget |
shmget key, size, flags |
require "ipc.ph"; require "shm.ph";
This function is available only on machines supporting System V IPC.
shmread |
shmread id, var, pos, size |
shmwrite |
shmwrite id, string, pos, size |
shutdown |
shutdown socket, how |
This function will not shut down your system; you'll have to execute an external program to do that. See system.
sin |
sin num |
sleep |
sleep n |
socket |
socket socket, domain, type, protocol |
use Socket;
This setting gives you the proper constants. The function returns true if successful.
socketpair |
socketpair sock1, sock2, domain, type, prtcl |
This function is typically used just before a fork. One of the resulting processes should close sock1, and the other should close sock2. You can use these sockets bidirectionally, unlike the filehandles created by the pipe function.
sort |
sort [code] list |
The normal calling code for subroutines is bypassed, with the following effects: the subroutine may not be a recursive subroutine, and the two elements to be compared are passed into the subroutine as $a and $b, not via @_. The variables $a and $b are passed by reference, so don't modify them in the subroutine.
Do not declare $a and $b as lexical variables (with my). They are package globals (though they're exempt from the usual restrictions on globals when you're using use strict). However, you do need to make sure your sort routine is in the same package, or else you must qualify $a and $b with the package name of the caller.
In versions preceding 5.005, Perl's sort is implemented in terms of C's qsort(3) function. Some qsort(3) versions will dump core if your sort subroutine provides inconsistent ordering of values. As of 5.005, however, this is no longer true.
splice |
splice @array, pos, [n], [list] |
split |
split /pattern/, string, [limit] |
If limit is specified and is not negative, the function splits into no more than that many fields. If limit is negative, it is treated as if an arbitrarily large limit has been specified. If limit is omitted, trailing null fields are stripped from the result (which potential users of pop would do well to remember). If string is omitted, the function splits the $_ string. If patternis also omitted, the function splits on whitespace, /\s+/, after skipping any leading whitespace.
If the pattern contains parentheses, then the substring matched by each pair of parentheses is included in the resulting list, interspersed with the fields that are ordinarily returned. Here's a simple case:
split /([-,])/, "1-10,20";
This produces the list value:
(1, '-', 10, ',', 20)
sprintf |
sprintf format, list |
%m.nx
in which m and n are optional sizes with interpretation that depends on the type of field, and xis one of the following:
Code |
Meaning |
---|---|
% |
Percent sign |
c |
Character |
d |
Decimal integer |
e |
Exponential format floating-point number |
E |
Exponential format floating-point number with uppercase E |
f |
Fixed-point format floating-point number |
g |
Floating-point number, in either exponential or fixed decimal notation |
G |
Like g with uppercase E (if applicable) |
ld |
Long decimal integer |
lo |
Long octal integer |
lu |
Long unsigned decimal integer |
lx |
Long hexadecimal integer |
o |
Octal integer |
s |
String |
u |
Unsigned decimal integer |
x |
Hexadecimal integer |
X |
Hexadecimal integer with uppercase letters |
p |
The Perl value's address in hexadecimal |
n |
Special value that stores the number of characters output so far into the next variable in the parameter list. |
sqrt |
sqrt num |
srand |
srand expr |
stat |
stat file |
($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size, $atime,$mtime,$ctime,$blksize,$blocks) = stat $filename;
Not all fields are supported on all filesystem types. Here are the meanings of the fields:
Field |
Meaning |
---|---|
dev |
Device number of filesystem |
ino |
Inode number |
mode |
File mode (type and permissions) |
nlink |
Number of (hard) links to the file |
uid |
Numeric user ID of file's owner |
gid |
Numeric group ID of file's owner |
rdev |
The device identifier (special files only) |
size |
Total size of file, in bytes |
atime |
Last access time since the epoch |
mtime |
Last modification time since the epoch |
ctime |
Inode change time (not creation time!) since the epoch |
blksize |
Preferred blocksize for file system I/O |
blocks |
Actual number of blocks allocated |
If stat is passed the special filehandle consisting of an underline, no actual stat is done, but the current contents of the stat structure from the last stat or stat-based file test (the -x operators) is returned.
study |
study scalar |
sub |
sub name [proto] {block} sub [proto] name |
substr |
substr string, pos, [n, replacement] |
You can use substr( ) as an lvalue—replacing the delimited substring with a new string—if string is given as an lvalue. You can also specify a replacement string in the fourth parameter to replace the substring. The original extracted substring is still returned.
symlink |
symlink oldfile, newfile |
syscall |
syscall list |
sysopen |
sysopen filehandle, filename, mode, [perms] |
The possible values and flag bits of the mode parameter are system-dependent; they are available via the Fcntl library module. However, for historical reasons, some values are universal: 0 means read-only, 1 means write-only, and 2 means read/write.
If the file named by filename does not exist, and sysopen creates it (typically because mode includes the O_CREAT flag), then the value of perms specifies the permissions of the newly created file. If perms is omitted, the default value is 0666, which allows read and write for all. This default is reasonable. See umask.
The FileHandle module provides a more object-oriented approach to sysopen. See also open.
sysread |
sysread filehandle, scalar, length, [offset] |
sysseek |
sysseek filehandle, offset, whence |
system |
system list |
syswrite |
syswrite filehandle, scalar, length, [offset] |
Do not mix calls to print (or write) and syswrite on the same filehandle unless you really know what you're doing.
tell |
tell filehandle |
telldir |
telldir dirhandle |
tie |
tie variable, classname, list |
A class implementing a hash should provide the following methods:
TIEHASH $class, LIST DESTROY $self FETCH $self, $key STORE $self, $key, $value DELETE $self, $key EXISTS $self, $key FIRSTKEY $self NEXTKEY $self, $lastkey
A class implementing an ordinary array should provide the following methods:
TIEARRAY $classname, LIST DESTROY $self FETCH $self, $subscript STORE $self, $subscript, $value
A class implementing a scalar should provide the following methods:
TIESCALAR $classname, LIST DESTROY $self FETCH $self, STORE $self, $value
Unlike dbmopen, the tie function will not use or require a module for you—you need to do that explicitly yourself.
tied |
tied variable |
ref tied %hash
to find out which package your hash is currently tied to.
time |
time |
times |
times |
($user, $system, $cuser, $csystem) = times;
For example, to time the execution speed of a section of Perl code:
$start = (times)[0]; ... $end = (times)[0]; printf "that took %.2f CPU seconds\n", $end - $start;
truncate |
truncate file, length |
uc |
uc string |
ucfirst |
ucfirst string |
umask |
umask expr |
umask((umask( ) & 077) | 7);
undef |
undef expr |
You may use undef as a placeholder on the left side of a list assignment, in which case the corresponding value from the right side is simply discarded. Apart from that, you may not use undef as an lvalue.
unlink |
unlink list |
unpack |
unpack template, string |
unshift |
unshift @array, list |
use |
use Module list use version use Module version list |
If version appears between Module and list, then use calls the version method in class Module with version as an argument.
Otherwise, use 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 the following:
BEGIN { require Module; import Module list; }
The BEGIN forces the require and import to happen at compile time. The require makes sure that the module is loaded into memory if it hasn't been yet. The import is not a built-in function—it's just an ordinary static method call into the package named by Module that tells the module to import the list of features back into the current package. The module can implement its import method any way it likes, though most modules just choose to derive their import method via inheritance from the Exporter class defined in the Exporter module.
If you don't want your namespace altered, explicitly supply an empty list:
use Module ( );
This is exactly equivalent to the following:
BEGIN { require Module; }
Because this is a wide-open interface, pragmas (compiler directives) are also implemented this way. (See Chapter 8, "Standard Modules" for descriptions of the currently implemented pragmas.) These pseudomodules typically import semantics into the current block scope, unlike ordinary modules, which import symbols into the current package. (The latter are effective through the end of the file.)
There's a corresponding declaration, no, that "unimports" any meanings originally imported by use but have since become less important:
no integer; no strict 'refs';
utime |
utime atime, mtime, files |
#!/usr/bin/perl $now = time; utime $now, $now, @ARGV;
To read the times from existing files, use stat.
values |
values %hash |
vec |
vec string, offset, bits |
The offset specifies the number of elements to skip over to find the one you want. bits is the number of bits per element in the vector, so each element can contain an unsigned integer in the range 0..(2**bits)-1. bits must be one of 1, 2, 4, 8, 16, or 32. As many elements as possible are packed into each byte, and the ordering is such that vec($vectorstring,0,1) is guaranteed to go into the lowest bit of the first byte of the string. To find the position of the byte in which an element will be placed, you have to multiply the offset by the number of elements per byte. When bits is 1, there are eight elements per byte. When bits is 2, there are four elements per byte. When bits is 4, there are two elements (called nybbles) per byte. And so on.
Regardless of whether your system is big-endian or little-endian, vec($foo, 0, 8) always refers to the first byte of string $foo. See select for examples of bitmaps generated with vec.
Vectors created with vec can also be manipulated with the logical operators |, &, ^, and ~, which will assume a bit vector operation is desired when the operands are strings. A bit vector (bits == 1) can be translated to or from a string of 1s and 0s by supplying a b* template to unpack or pack. Similarly, a vector of nybbles (bits == 4) can be translated with an h* template.
wait |
wait |
$SIG{CHLD} = sub { wait };
If you expected a child and didn't find it, you probably had a call to system, a close on a pipe, or backticks between the fork and the wait. These constructs also do a wait(2) and may have harvested your child process. Use waitpid to avoid this problem.
waitpid |
waitpid pid, flags |
use POSIX "sys_wait_h";
On systems that implement neither the waitpid(2) nor the wait4(2) system call, flags may be specified only as 0. In other words, you can wait for a specific pid, but you can't do it in nonblocking mode.
wantarray |
wantarray |
warn |
warn msg |
warn "Debug enabled" if $debug;
If the message supplied is null, the message "Something's wrong" is used. As with die, a message not ending with a newline will have file and line number information automatically appended. The warn operator is unrelated to the -w switch.
write |
write filehandle |
If filehandle is unspecified, output goes to the current default output filehandle, which starts as STDOUT but may be changed by the select operator. If the filehandle is an expression, then the expression is evaluated to determine the actual filehandle at runtime.
Note that write is not the opposite of read. Use print for simple string output. If you want to bypass standard I/O, see syswrite.
Copyright © 2002 O'Reilly & Associates. All rights reserved.