Alphabetical Listing of Perl Functions

-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 non-zero 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). -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() in order 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 _; 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
Returns the absolute value of its argument.

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 ``Sockets: Client/Server Communication''.

alarm SECONDS
Arranges to have a SIGALRM delivered to this process after the specified number of seconds have elapsed. (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 select below. It is not advised to intermix alarm() and sleep() calls.

atan2 Y,X
Returns the arctangent of Y/X in the range -PI to PI.

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 ``Sockets: Client/Server Communication''.

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 DOS and similarly archaic systems, it may be imperative--otherwise your 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 referenced object (passed as 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, since a bless() is often the last 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 TRUE if there is a caller, that is, if we're in a subroutine or eval() or require() , and FALSE 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, $wantargs) = caller($i);

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 that 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. Returns the number of files successfully changed.

$cnt = chmod 0755, 'foo', 'bar'; chmod 0755, @executables;

chomp VARIABLE

chomp LIST

chomp
This is a slightly safer version of chop (see below). 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 number of characters removed. 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(/:/); ... }

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 non-numeric 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
Returns the character represented by that NUMBER in the character set. For example, chr(65) is ``A'' in ASCII.

chroot FILENAME
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 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, since 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. 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 status value of the command into $? . Example:

open(OUTPUT, '|sort >foo'); # pipe to sort ... # print stuff to output close OUTPUT; # wait for sort to finish open(INPUT, 'foo'); # get sort's results

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 ``Sockets: Client/Server Communication''.

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 $_ .

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.

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 is unwise.

dbmclose ASSOC_ARRAY
[This function has been superseded by the untie() function.]

Breaks the binding between a DBM file and an associative array.

dbmopen ASSOC,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 an associative array. ASSOC is the name of the associative array. (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 only supports 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 associative array variables, not set them. If you want to test whether you can write, either use file tests or try setting a dummy array 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 AnyDBM_File for a more general description of the pros and cons of the various dbm apparoches, as well as DB_File for a particularly rich implementation.

defined EXPR
Returns a boolean value saying whether EXPR has a real value or not. Many operations return the undefined value under exceptional conditions, such as end of file, uninitialized variable, system error and such. This function allows you to distinguish between an undefined null scalar and a defined null scalar with operations that might return a real null string, such as referencing elements of an array. You may also check to see if arrays or subroutines exist. Use of defined on predefined variables is not guaranteed to produce intuitive results.

When used on a hash array element, it tells you whether the value is defined, not whether the key exists in the hash. Use exists() for that.

Examples:

print if defined $switch{'D'}; print "$val\n" while defined($val = pop(@ary)); die "Can't readlink $sym: $!" unless defined($value = readlink $sym); eval '@foo = ()' if defined(@foo); die "No XYZ package defined" unless defined %_XYZ; sub foo { defined &$bar ? &$bar(@_) : die "No bar"; }

See also undef() .

delete EXPR
Deletes the specified value from its hash array. Returns the deleted value, or the undefined value if nothing was deleted. Deleting from $ENV{} modifies the environment. Deleting from an array 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 an associative array:

foreach $key (keys %ARRAY) { delete $ARRAY{$key}; }

(But it would be faster to use the undef() command.) Note that the EXPR can be arbitrarily complicated as long as the final operation is a hash key lookup:

delete $ref->[$x][$y]{$key};

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 ``, 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() .

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 .

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

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 Predefined Names ). 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'; QUICKSTART: Getopt('f');

each ASSOC_ARRAY
Returns a 2-element array consisting of the key and value for the next value of an associative array, so that you can iterate over it. Entries are returned in an apparently random order. When the array is entirely read, a null array is returned (which when assigned produces a FALSE (0) value). The next call to each() after that will start iterating again. The iterator can be reset only by reading all the elements from the array. You should not add elements to an array while you're iterating over it. There is a single iterator for each associative array, shared by all each() , keys() and values() function calls in the program. 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 pseudofile 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:

# 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. Testing eof

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, subroutine or 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.

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.

Note that, since 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 eval-BLOCK form to trap run-time errors without incurring the penalty of recompiling each time. The error, if any, is still returned in $@ . Examples:

# make divide-by-zero non-fatal 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 $@

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 at all. (Case 4 is preferred for purely visual reasons.) Case 5 is a place where normally you WOULD like to use double quotes, except that in that particular 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 the system() function if you want it to return.

If there is more than one argument in LIST, or if