[Copyright Information] [Table of Contents] [Que Home Page]
[Prev Chapter] [Next Chapter]

15 - Function List

Perl has a large number of functions which come as standard with most implementations, and an even wider range of additional modules each with its own additional functions. This chapter lists all the standard functions alphabetically for reference.

Each function is assigned a category. There are two main categories, list operators which can take more than one argument, and named unary operators which can only take one argument. A secondary category is noted in parentheses so you can see at a glance the type of operation the function performs. This is a very rough categorization, as many functions might overlap in any category scheme.

For each function the form of its arguments are listed. If there are multiple forms of calling the function there will be multiple lines describing each one. The meaning of the arguments is described in the text.

The type of value returned by the function is listed. This is usually specified in more detail in the function description.

Two categories of function, those dealing with sockets, and those dealing with System V inter process communications are not dealt with in great detail. These are nearly all direct counterparts of unix system calls, and are not considered central to this book on Perl for Web Programming.

The chapter includes:

-A

Category: named unary operator (file test)

Arguments: handle

Arguments: filename

Arguments: none

Return value: integer (age of file in days since last access relative to $BASETIME)

Filetest operator takes one filehandle or filename as an argument. Returns the age of file in days since last access relative to $BASETIME. All filetest operators can take a special argument underscore (_) which means that the test is carried out on the same filehandle as the last filetest, stat() or lstat() call. If no argument is supplied $_ is used.

Example:

print "-A ", -A "/etc/fstab", "\n";

-B

Category: named unary operator (file test)

Arguments: handle

Arguments: filename

Arguments: none

Return value: 1 (true) '' (false)

Filetest operator takes one filehandle or filename as an argument. Returns 1 (true) if file is binary. Returns '' (false) if file is not binary. The first characters of the file are checked to see if the high bit is set and if a suitable number are the file is assumed to be binary. If the file is empty it is returned as being binary. As this test involves reading the file itself it is best to test if the file exists as a plain file (-f) first. All filetest operators can take a special argument underscore (_) which means that the test is carried out on the same filehandle as the last filetest, stat() or lstat() call. If no argument is supplied $_ is used.

Example:

(-B "/etc/fstab") ? print("-B fstab is binary\n") : print("-B fstab is not binary\n");

-b

Category: named unary operator (file test)

Arguments: handle

Arguments: filename

Arguments: none

Return value: 1 (true) '' (false)

Filetest operator takes one filehandle or filename as an argument. Returns 1 (true) if file is a block special file (i.e. a unix /dev device file). Returns '' (false) if file is not a block special file. All filetest operators can take a special argument underscore (_) which means that the test is carried out on the same filehandle as the last filetest, stat() or lstat() call. If no argument is supplied $_ is used.

Example:

(-b "/dev/hda1") ? print("-b hda1 is block\n") : print("-b hda1 is not block\n");

-c

Category: named unary operator (file test)

Arguments: handle

Arguments: filename

Arguments: none

Return value: 1 (true) '' (false)

Filetest operator takes one filehandle or filename as an argument. Returns 1 (true) if file is a character special file. Returns '' (false) if file is not a character special file. All filetest operators can take a special argument underscore (_) which means that the test is carried out on the same filehandle as the last filetest, stat() or lstat() call. If no argument is supplied $_ is used.

Example:

(-c "/dev/tty0") ? print("-c tty0 is char\n") : print("-c tty0 is not char\n");

-C

Category: named unary operator (file test)

Arguments: handle

Arguments: filename

Arguments: none

Return value: integer (age of file in days since last inode change relative to $BASETIME)

Filetest operator takes one filehandle or filename as an argument. Returns age of file in days since last inode change relative to $BASETIME. All filetest operators can take a special argument underscore (_) which means that the test is carried out on the same filehandle as the last filetest, stat() or lstat() call. If no argument is supplied $_ is used.

Example:

print "-C ", -C "/etc/fstab", "\n";

-d

Category: named unary operator (file test)

Arguments: handle

Arguments: filename

Arguments: none

Return value: 1 (true) '' (false)

Filetest operator takes one filehandle or filename as an argument. Returns 1 (true) if file is a directory. Returns '' (false) if file is not a directory. All filetest operators can take a special argument underscore (_) which means that the test is carried out on the same filehandle as the last filetest, stat() or lstat() call. If no argument is supplied $_ is used.

Example:

(-d "/") ? print("-d / is dir\n") : print("-d / is not dir\n");

-e

Category: named unary operator (file test)

Arguments: handle

Arguments: filename

Arguments: none

Arguments: none

Return value: 1 (true) '' (false)

Filetest operator takes one filehandle or filename as an argument. Returns 1 (true) if file exists. Returns '' (false) if file does not exist. All filetest operators can take a special argument underscore (_) which means that the test is carried out on the same filehandle as the last filetest, stat() or lstat() call. If no argument is supplied $_ is used.

Example:

(-e "/") ? print("-e / exists\n") : print("-e / exists\n");

-f

Category: named unary operator (file test)

Arguments: handle

Arguments: filename

Arguments: none

Category: named unary operator (file test)

Return value: 1 (true) '' (false)

Filetest operator takes one filehandle or filename as an argument. Returns 1 (true) if file is a plain file. Returns '' (false) if file is not a plain file. A plain file is any file which is not a special block device (-b), a special character device (-c), a directory (-d), a symbolic link (-l), a pipe (-p), a named socket (-S), or a direct link to an I/O terminal (-t). All filetest operators can take a special argument underscore (_) which means that the test is carried out on the same filehandle as the last filetest, stat() or lstat() call. If no argument is supplied $_ is used.

Example:

(-f "/") ? print("-f / is plain\n") : print("-f / is not plain\n");

-g

Category: named unary operator (file test)

Arguments: handle

Arguments: filename

Arguments: none

Return value: 1 (true) '' (false)

Filetest operator takes one filehandle or filename as an argument. Returns 1 (true) if file has the setgid bit set. Returns '' (false) if file does not have the setgid bit set. In unix setgid allows an executable to take on the group of the group ownership of the executable itself while executing. All filetest operators can take a special argument underscore (_) which means that the test is carried out on the same filehandle as the last filetest, stat() or lstat() call. If no argument is supplied $_ is used.

Example:

(-g "/vmlinuz") ? print("-g /vmlinuz has setgid\n") : print("-g /vmlinuz has not setgid\n");

-k

Category: named unary operator (file test)

Arguments: handle

Arguments: filename

Arguments: none

Return value: 1 (true) '' (false)

Filetest operator takes one filehandle or filename as an argument. Returns 1 (true) if the sticky bit is set. Returns '' (false) if the sticky bit is not set. In unix, the sticky bit can mark an executable file to be held in memory when exited. This is normally set for frequently used commands to optimize execution speed. All filetest operators can take a special argument underscore (_) which means that the test is carried out on the same filehandle as the last filetest, stat() or lstat() call. If no argument is supplied $_ is used.

Example:

(-k "/vmlinuz") ? print("-k /vmlinuz is sticky\n") : print("-k /vmlinuz is not sticky\n");

-l

Category: named unary operator (file test)

Arguments: handle

Arguments: filename

Arguments: none

Return value: 1 (true) '' (false)

Filetest operator takes one filehandle or filename as an argument. Returns 1 (true) if the file is a symbolic link. Returns '' (false) if the file is not a symbolic link. All filetest operators can take a special argument underscore (_) which means that the test is carried out on the same filehandle as the last filetest, stat() or lstat() call. If no argument is supplied $_ is used.

Example:

(-l "/vmlinuz") ? print("-l /vmlinuz is symlink\n") : print("-l /vmlinuz is not symlink\n");

-M

Category: named unary operator (file test)

Arguments: handle

Arguments: filename

Arguments: none

Return value: integer (age of file in days relative to $BASETIME)

Filetest operator takes one filehandle or filename as an argument. Returns the age of the file in days, relative to $BASETIME. All filetest operators can take a special argument underscore (_) which means that the test is carried out on the same filehandle as the last filetest, stat() or lstat() call. If no argument is supplied $_ is used.

Example:

print "-M ", -M "/etc/fstab", "\n";

-o

Category: named unary operator (file test)

Arguments: handle

Arguments: filename

Arguments: none

Return value: 1 (true) '' (false)

Filetest operator takes one filehandle or filename as an argument. Returns 1 (true) if the file is owned by the effective uid/gid and '' (false) otherwise. For the superuser it always returns true. All filetest operators can take a special argument underscore (_) which means that the test is carried out on the same filehandle as the last filetest, stat() or lstat() call. If no argument is supplied $_ is used.

Example:

(-O "/vmlinuz") ? print("-O /vmlinuz is owned by effective uid/gid\n") : print("-o /vmlinuz is not owned by effective uid/gid\n");

-O

Category: named unary operator (file test)

Arguments: handle

Arguments: filename

Arguments: none

Return value: 1 (true) '' (false)

Filetest operator takes one filehandle or filename as an argument. Returns 1 (true) if the file is owned by the real uid/gid and '' (false) otherwise. For the superuser it always returns true.. All filetest operators can take a special argument underscore (_) which means that the test is carried out on the same filehandle as the last filetest, stat() or lstat() call. If no argument is supplied $_ is used.

Example:

(-o "/vmlinuz") ? print("-o /vmlinuz is owned by real uid/gid\n") : print("-o /vmlinuz is not owned by real uid/gid\n");

-p

Category: named unary operator (file test)

Arguments: handle

Arguments: filename

Arguments: none

Return value: 1 (true) '' (false)

Filetest operator takes one filehandle or filename as an argument. Returns 1 (true) if file is a named pipe. Returns '' (false) if file is not a named pipe. All filetest operators can take a special argument underscore (_) which means that the test is carried out on the same filehandle as the last filetest, stat() or lstat() call. If no argument is supplied $_ is used.

Example:

(-p "/vmlinuz") ? print("-p /vmlinuz is named pipe\n") : print("-p /vmlinuz is not named pipe\n");

-R

Category: named unary operator (file test)

Arguments: handle

Arguments: filename

Arguments: none

Return value: 1 (true) '' (false)

Filetest operator takes one filehandle or filename as an argument. Returns 1 (true) if file is readable by the effective uid/gid and '' (false) otherwise. For the superuser it always returns true. All filetest operators can take a special argument underscore (_) which means that the test is carried out on the same filehandle as the last filetest, stat() or lstat() call. If no argument is supplied $_ is used.

Example:

(-R "/vmlinuz") ? print("-R /vmlinuz is readable by effective uid/gid\n") : print("-R /vmlinuz is not readable by effective uid/gid\n");

-r

Category: named unary operator (file test)

Arguments: handle

Arguments: filename

Arguments: none

Return value: 1 (true) '' (false)

Filetest operator takes one filehandle or filename as an argument. Returns 1 (true) if file is readable by the real uid/gid and '' (false) otherwise. For the superuser it always returns true. All filetest operators can take a special argument underscore (_) which means that the test is carried out on the same filehandle as the last filetest, stat() or lstat() call. If no argument is supplied $_ is used.

Example:

(-r "/vmlinuz") ? print("-r /vmlinuz is readable by real uid/gid\n") : print("-r /vmlinuz is not readable by real uid/gid\n");

-s

Category: named unary operator (file test)

Arguments: handle

Arguments: filename

Arguments: none

Return value: integer (size) '' (false)

Filetest operator takes one filehandle or filename as an argument. Returns size in bytes as an integer if file has a non-zero size. Returns '' (false) if file has zero size. All filetest operators can take a special argument underscore (_) which means that the test is carried out on the same filehandle as the last filetest, stat() or lstat() call. If no argument is supplied $_ is used.

Example:

(-s "/vmlinuz") ? print("-s /vmlinuz has non-zero size\n") : print("-s /vmlinuz does not have non-zero size\n");

-S

Category: named unary operator (file test)

Arguments: handle

Arguments: filename

Arguments: none

Return value: 1 (true) '' (false)

Filetest operator takes one filehandle or filename as an argument. Returns 1 (true) if file is a symbolic link. Returns '' (false) if file is not a symbolic link. All filetest operators can take a special argument underscore (_) which means that the test is carried out on the same filehandle as the last filetest, stat() or lstat() call. If no argument is supplied $_ is used.

Example:

(-S "/vmlinuz") ? print("-S /vmlinuz is socket\n") : print("-S /vmlinuz is not socket\n");

-T

Category: named unary operator (file test)

Arguments: handle

Arguments: filename

Arguments: none

Return value: 1 (true) '' (false)

Filetest operator takes one filehandle or filename as an argument. Returns 1 (true) if file is a text file. Returns '' (false) if file is not a text file. The first characters of the file are checked to see if the high bit is set and if a suitable number are not set the file is assumed to be text. If the file is empty true is returned. As this test involves reading the file itself it is best to test if the file exists as a plain file (-f) first. All filetest operators can take a special argument underscore (_) which means that the test is carried out on the same filehandle as the last filetest, stat() or lstat() call. If no argument is supplied $_ is used.

Example:

(-T "/vmlinuz") ? print("-T /vmlinuz is text file\n") : print("-T /vmlinuz is not text file\n");

-t

Category: named unary operator (file test)

Arguments: handle

Arguments: filename

Arguments: none

Return value: 1 (true) '' (false)

Filetest operator takes one filehandle or filename as an argument. Returns 1 (true) if the file is a terminal tty device. Returns '' (false) if the file is not. All filetest operators can take a special argument underscore (_) which means that the test is carried out on the same filehandle as the last filetest, stat() or lstat() call. If no argument is supplied STDIN is used.

Example:

(-t "/vmlinuz") ? print("-t /vmlinuz is tty\n") : print("-t /vmlinuz is not tty\n");

-u

Category: named unary operator (file test)

Arguments: handle

Arguments: filename

Arguments: none

Return value: 1 (true) '' (false)

Filetest operator takes one filehandle or filename as an argument. Returns 1 (true) if the file has the setuid bit set. Returns '' (false) if the files does not have the setuid bit set. In unix setuid allows an executable to take on the uid of the user ownership of the executable itself while executing. All filetest operators can take a special argument underscore (_) which means that the test is carried out on the same filehandle as the last filetest, stat() or lstat() call. If no argument is supplied $_ is used.

Example:

(-u "/vmlinuz") ? print("-u /vmlinuz has suid set\n") : print("-u /vmlinuz does not have suid set\n");

-w

Category: named unary operator (file test)

Arguments: handle

Arguments: filename

Arguments: none

Return value: 1 (true) '' (false)

Filetest operator takes one filehandle or filename as an argument. Returns 1 (true) if the file is writable by the effective uid/gid. Returns '' (false) otherwise. For the superuser it always returns true. All filetest operators can take a special argument underscore (_) which means that the test is carried out on the same filehandle as the last filetest, stat() or lstat() call. If no argument is supplied $_ is used.

Example:

(-w "/vmlinuz") ? print("-w /vmlinuz is writable by effective uid/gid\n") : print("-l /vmlinuz is not writable by effective uid/gid\n");

-W

Category: named unary operator (file test)

Arguments: handle

Arguments: filename

Arguments: none

Return value: 1 (true) '' (false)

Filetest operator takes one filehandle or filename as an argument. Returns 1 (true) if the file is writable by the real uid/gid. Returns '' (false) otherwise. For the superuser it always returns true. All filetest operators can take a special argument underscore (_) which means that the test is carried out on the same filehandle as the last filetest, stat() or lstat() call. If no argument is supplied $_ is used.

Example:

(-W "/vmlinuz") ? print("-W /vmlinuz is writable by real uid/gid\n") : print("-W /vmlinuz is not writable by real UID/GID\n");

-x

Category: named unary operator (file test)

Arguments: handle

Arguments: filename

Arguments: none

Return value: 1 (true) '' (false)

Filetest operator takes one filehandle or filename as an argument. Returns 1 (true) if the file is executable by the effective uid/gid. Returns '' (false) otherwise. For the superuser it always returns true. All filetest operators can take a special argument underscore (_) which means that the test is carried out on the same filehandle as the last filetest, stat() or lstat() call. If no argument is supplied $_ is used.

Example:

(-x "/bin/ls") ? print("-x /bin/ls is executable by effective uid/gid\n") : print("-x /bin/ls is not executable by effective uid/gid\n");

-X

Category: named unary operator (file test)

Arguments: handle

Arguments: filename

Arguments: none

Return value: 1 (true) '' (false)

Filetest operator takes one filehandle or filename as an argument. Returns 1 (true) if the file is executable by the real uid/gid. Returns '' (false) otherwise. For the superuser it always returns true. All filetest operators can take a special argument underscore (_) which means that the test is carried out on the same filehandle as the last filetest, stat() or lstat() call. If no argument is supplied $_ is used.

Example:

(-X _) ? print("-X /bin/ls is executable by real uid/gid\n") : print("-X /bin/ls is not executable by real uid/gid\n");

-z

Category: named unary operator (file test)

Arguments: handle

Arguments: filename

Arguments: none

Return value: 1 (true) '' (false)

Filetest operator takes one filehandle or filename as an argument. Returns 1 (true) if the file has zero size. Returns '' (false) otherwise. All filetest operators can take a special argument underscore (_) which means that the test is carried out on the same filehandle as the last filetest, stat() or lstat() call. If no argument is supplied $_ is used.

Example:

(-z "/vmlinuz") ? print("-z /vmlinuz has zero size\n") : print("-z /vmlinuz does not have zero size\n");

abs

Category: named unary operator (numeric)

Arguments: numeric value

Return value: numeric

Returns absolute value of its argument (i.e. ignoring any sign).

Example:

print("abs(-10) = ",abs(-10),"\n");

accept

Category: list operator (socket)

Arguments: newsocket, genericsocket

Return value: integer (address of socket), '' (false)

Performs low-level unix socket call as accept().

alarm

Category: named unary operator (process)

Arguments: integer (seconds)

Return value: integer (seconds to previous alarm)

Sets up a unix SIGALRM signal to be generated in the number of seconds specified. It is possible for Perl to trap such signals call specific signal handling subroutines, c.f. trap(). Subseqent calls reset the alarm() time, retaining the number of seconds which were needed before the previous SIGALRM would have been generated. A call with zero seconds as an argument cancels the current alarm().

Example:

print("alarm(10) ",alarm(10)," (to illustrate it needs to trapped c.f. trap)\n");

atan2

Category: list operator (numeric)

Arguments: numeric, numeric

Return value: numeric

Returns the arctangent of the arguments.

Example:

print("atan2(60,2) = ",atan2(60,2),"\n");

bind

Category: list operator (socket)

Arguments: sockethandle, numeric (network address)

Return value: 1 (true) '' (false)

Binds a network address to the socket handle. As unix bind() call.

binmode

Category: named unary operator (i/o)

Arguments: handle

Return value: 1 (success) or undefined (error)

On systems which distinguish between text and binary files this functions forces binary mode treatment of the given file handle. In systems which do make the distinction text files have the end of line characters (Carriage Return, Linefeed) automatically translated to the unix end of line character (Linefeed) when reading from the file (and vice versa when writing to the file); binary mode files do have this automatic transformation.

Example:

open(FIL,"file.dat");
binmode(FIL);

bless

Category: list operator (class)

Arguments: variable

Arguments: variable, classname

Return value: reference

Assigns a class to the referenced object. This class is either explicitly stated in the call, or the name of the current package is used if a second argument is not used in the call. The reference is returned.


Explictly state the class (use the two argument version of the call) if the code could be inherited by other classes, as the class in the single argument call would not return the required value.

Example:

$tmp = {};
bless $tmp, ATMPCLASS;
print "bless() \$tmp is now in class ",ref($tmp),"\n";

caller

program)

Category: named unary operator (scope)

Arguments: expression

Arguments: none

Return value: TRUE FALSE

Return value: (package, filename, line)

This function is used to test the current scope of a subroutine call. If evaluated in a scalar context returns TRUE or FALSE depending on whether the current code has been called as a subroutine (this includes code which is included using a require() or an eval() call). In a list context it supplies details of the calling context in a list comprising the package name, file name, and line of the call.

Example:

sub testcaller {
    ($package, $file, $line) = caller;
}
&testcaller;
print "caller() Package=$package File=$file Line=$line \n";

chdir

Category: named unary operator (files)

Arguments: expression

Arguments: none

Return value: TRUE/FALSE

Changes the current directory to the directory specified. If no argument is given changes to the home directory of the current user. Returns TRUE on success and FALSE otherwise.

Example:

chdir("/") ? print("It worked.\n") : print("It didn't work.\n");

chmod

Category: list operator (files)

Arguments: list

Return value: numeric

The first element in the list is the unix octal number representing the file permission. This function applies this to all the files in the following list. It returns the number of files successfully modified.

Example:

print "chmod() changed ", chmod(0744,"/tmp/test1.txt","/tmp/test2.txt")," files.\n";

chomp

Category: list operator (string)

Arguments: list

Arguments: variable

Arguments: none

Return value: numeric

This is an alternative to the chop() function. It removes characters at the end of strings corresponding to the $INPUT_LINE_SEPARATOR ($/). It returns the number of characters removed. It can be given a list of strings upon which to perform this operation. When given no arguments the operation is performed on $_.

Example:

$tmp="Aaagh!\n";
$ret = chomp $tmp;
print("chomp() ", $tmp, " returned ", $ret, "\n");

chop

Category: list operator (string)

Arguments: list

Arguments: variable

Arguments: none

Return value: character

This function removes the last character of a string and returns that character. If given a list of arguments, the operation is performed on each one and the last character chopped is returned.

Example:

$tmp = "1234";
$ret = chop $tmp;
print("chop() ", $tmp, " returned ", $ret, "\n");

Use chomp() (with $/ set to "\n") rather than chop() if you are not sure that the string has a trailing newline or not as chop() will remove the last character regardless, but chomp() will only remove it if it is a newline.

chown

Category: list operator (files)

Arguments: list

Return value: numeric

This function changes the ownership of the specified files. The first two elements of the list defined the user ID and the groupid to set this ownership to, the subsequent items in the list are the filenames which are changed. The return value is the number of files successfully changed.

Example:

print("chown() "); 
chown(1,1,"/tmp/test1.txt") ? print("Worked\n") : print("Didn't work\n");

chr

Category: named unary operator (string)

Arguments: numeric

Return value: character

Returns the character indicated by the numeric argument.

Example:

$E = chr(69);
print("chr() $E \n");

chroot

Category: named unary operator (files)

Arguments: directoryname

Arguments: none

Return value: TRUE/FALSE

This is equivalent to the unix chroot() function. Given a directory name, this directory is treated as the root directory by all subseqent file system references (thus effectively hiding the rest of the file system outside the specified directory). This restriction will apply to all subprocesses of the current process as well.


Normal unix security limits this function to the superuser, and it is normally used to make processes safer by only allowing them access to the subdirectory tree relevant to their purpose.

Example:

print("chroot() ");
chroot("/") ? print("Worked.\n") : print("Didn't work.\n");

close

Category: named unary operator (files)

Arguments: handle

Return value: TRUE/FALSE

Closes the file opened with the filehandle. This operation flushes all buffered output. If the file handle refers to a pipe the Perl program waits until the process being piped to has finished.

Example:

open(INF,"/tmp/test1.txt");
$ret = close(INF);
print("close() Returned ",$ret," on success\n");

closedir

Category: named unary operator (file)

Arguments: handle

Return value: TRUE/FALSE

Closes the directory opened by opendir() by specifying the relevant directory handle.

Example:

opendir(IND,"/tmp");
$ret = closedir(IND);
print("closedir() Returned ",$ret," on success\n");

connect

Category: list operator (socket)

Arguments: socket, name

Return value: TRUE/FALSE

This is equivelent to the unix function call.

continue

Category: flow control

Arguments: block

Return value: n/a

A continue block is a syntax structure which allows a condition to be attached to another block (normally a while block). Any statements in the continue block are evaluated before the attached block is repeated.

Example:

$i=0;
print "continue() ";
while ($i<10) {
      if ($i % 2)
         { print "${i}o "; next; }
      else
         {print "${i}e ";}
} continue {$i++}
print "\n";

cos

Category: named unary operator (numeric)

Arguments: expression

Return value: numeric

Returns the cosine value of the numeric expression supplied as an argument.

Example:

print "cos() ",cos(60),"\n";

crypt

Category: list operator

Arguments: string, string

Return value: string

This is equivalent to the crypt() unix call (where available). It encrypts a string (the first argument) using a key (usually the first two letters of the first string itself) and returns the encrypted string.

Example:

print "crypt() Password PA: ",crypt("Password","PA"),"\n";

dbmclose

Category: named unary operator (i/o)

Arguments: arrayname

Return value: TRUE/FALSE

This function undoes the linking of an associative array to a dbm file (see dbmopen()).


This is depreciated in Perl 5, use tie() instead.

dbmopen

Category: list operator (i/o)

Arguments: arrayname, dbname, mode

Return value: fatal error if dbm not supported (Perl 4)

Links the associative array referred to by arrayname to the dbm database (or equivalent) referred to by dbname (this name should not include the suffix). If the database does not exist a new one with the specified mode will be opened (the mode being an octal chmod() style file protection).


This is depreciated in Perl 5, use tie() instead.

defined

Category: named unary operator (misc)

Arguments: expression

Return value: TRUE/FALSE

This function returns a Boolean value depending on whether the argument is defined or not. There is a subtle distinction between an undefined and a defined null value. Some functions return undefined null to indicate errors, while others return a defined null to indicate a particular result (use a comparison with the null string to test for this rather than using defined())

Example

@iexist = (1,2,3);
print("defined() The array \@iexist ");
defined @iexist ? print("exists.\n") : print("does not exist.\n");

delete

Category: named unary operator (hash)

Arguments: expression

Return value: value

Delete an element from a hash array, given the key for the element to delete, returning the value of the deleted element.

Example:

%Hash = (1, One, 2, Two, 3, Three);
print("delete() Deleted ",delete($Hash{1}),"\n");

die

program)

Category: list operator (i/o)

Arguments: list

Return value: errorlevel

This function terminates execution of the Perl script when called printing the value of the list argument to STDERR (as if called with print(STDERR, list)). The exit value is the current value of $OS_ERROR ($!) which may have been set by a previous function. If this has a value of zero it returns $CHILD_ERROR ($?). If this is zero it exits with errorlevel 255. If the error message string specified by the list does not end in a newline, the text "at $PROGRAM_NAME at line <line>" where <line> is the line number of the Perl script.

Example:

die("die() Now we can give an example of die()...exiting");

do

Category: (flow)

Arguments: block

Arguments: subroutine(list)

Arguments: expression

Return value: special

This is a syntax structure which allows repeated execution of a block of statements. The value returned is the result of the last statement in the block. Normally an exit condition is supplied after the block. The second form where the argument is subroutine() is a depreciated form. The third form executes the contents of the filename specified by the expression (but it is better to use use() or require() instead as this has better error checking).

Example:

$i=1;
print("do ");
$return = do {
  print $i, " ";
  $i++;
} until $i==3;
print("Returned $return\n");

dump

Category: named unary operator (misc)

Arguments: label

Return value: n/a

This causes the program to create a binary image core dump. This then allows the dumped image to be reloaded using the undump() function (if supported) which can effectively allow the use of precompiled Perl images. When reloaded the program begins execution from the label specified. So it is possible to set up a program which initializes data structures to dump() after the initialization so that execution is faster when reloading the dumped image.

each

Category: named unary operator (hash)

Arguments: variable

Return value: key, value

This function allows iteration over the elements in an associative array. Each time it is evaluated it returns another list of two elements (a key, value pair from the associative array). When all the elements have been returned it returns a null list.

Example:

%NumberWord = (1, One, 2, Two, 3, Three);
print("each() ");
while (($number,$wordform)=each(%NumberWord)) {
  print("$number:$wordform ");
}
print("\n");

endgrent

Category: (system files)

Arguments: none

Return value: TRUE/FALSE

Closes the /etc/group file used by getgrent() and other group related functions. Equivalent to the unix system call.

Example:

($name,$pw,$gid,@members)=getgrent();
$returned = endgrent();
print("endgrent() Closes /etc/group [$name,$gid] file returning $returned.\n");

endhostent

Category: (system files)

Arguments: none

Return value: TRUE/FALSE

Closes the TCP socket used by name server queries gethostbyname() and host related functions. Equivalent to the unix system call.

Example:

$host = gethostbyname("lynch");
$returned = endhostent();
print("endhostent() Closes /etc/hosts [$host] returning $returned.\n");

endnetent

Category: (system files)

Arguments: none

Return value: TRUE/FALSE

Closes the /etc/networks file used by getnetent() and network related functions. Equivalent to the unix system call.

Example:

($name,$alias,$net,$net) = getnetent();
$returned = endnetent();
print("endnetent() Closes /etc/networks [$name] returning $returned.\n");

endprotoent

Category: (system files)

Arguments: none

Return value: TRUE/FALSE

Closes the /etc/protocols file used by getprotoent() and protocol related functions. Equivalent to the unix system call.

Example:

($name, $alias, $protocol) = getprotoent();
$returned = endprotoent();
print("endprotoent() Closes /etc/protocols [$name,$alias,$protocol] file returning $returned.\n");

endpwent

Category: (system files)

Arguments: none

Return value: TRUE/FALSE

Closes the /etc/passwd file used by getpwent() and password related functions. Equivalent to the unix system call.

Example:

($name,$pass,$uid,$gid,$quota,$name,$gcos,$logindir,$shell) = getpwent();
$returned = endpwent();
print("endpwent() Closes /etc/passwd [$logindir,$shell] file returning $returned.\n");

endservent

Category: (system files)

Arguments: none

Return value: TRUE/FALSE

Closes the /etc/servers file used by getservent() and related functions. Equivalent to the unix system call.

Example:

($name,$aliases,$port,$protocol) = getservent();
$returned = endservent();
print("endservent() Closes /etc/servers [$name] file returning $returned.\n");

eof

Category: named unary operator (i/o)

Arguments: handle

Arguments: ()

Arguments: none

Return value: TRUE/FALSE

Tests if the file specified by the file handle is at the and of file. This is done by reading the next character and then undoing this operation (so is only suitable on files where this can be done safely). If no argument is supplied the file tested is the last file which was read. If the empty list is supplied then this tests if all the last file suppiled an argument to the Perl script are eof() (i.e. it can be used as a termination condition in a while (<>) {} loop).

Example:

open INF, "/tmp/test1.txt";
if (eof INF) 
  {print "eof() TRUE\n";}
else
  {print "eof() FALSE\n";}        
close INF;

eval

Category: named unary operator (flow)

Arguments: expression

Arguments: block

Arguments: none

Return value: special

This function treats the expression like a Perl program and executes it returning the return value of the last statement executed. As the context of this execution is the same as that of the script itself, variable definitions and subroutine definitions persist. Syntax errors and runtime errors (including die()) are trapped and an undefined result is returned. If such an error does occur $EVAL_ERROR ($@) is set. $@ will be equal to a defined null string if no errors are found. If no expression is supplied, $_ is the default argument. If the block syntax is used then the expressions in the block are evaluated only once within the script (which may be more efficient for certain situations).


eval() traps possible error conditions which would otherwise crash a program and so can be used to test if certain features are available which would cause runtime errors if used when not available.

Example:

$ans = 3;
eval "$ans = ;";
if ($@ eq "")
  {print "eval() returned success.\n";}
else
  {print "eval() error: $@";}

exec

Category: list operator (process)

Arguments: list

Return value: n/a

This function passes control from the script to an external system command. There is no retain from this call so there is no return value. Note that system() calls external commands and does return.

This is equivalent to the unix system call execvp().

Example:

exec("cat /etc/motd");

exists

Category: named unary operator (hash)

Arguments: expression

Return value: TRUE/FALSE

Tests whether a given key value exists in an associative array, returning a Boolean value.

Example:

%test = ( One, 1, Two, 2);
if (exists $test{One}) 
  {print "exists() returned success.\n";}
else
  {print "exists() returned an error.\n";}

exit

Category: named unary operator (flow)

Arguments: expression

Arguments: none

Return value: value

This function evaluates the expression given as an argument and exits the program with that error. The default value for the error is 0 if no argument is supplied. Note that die() allows an error message.

Example:

exit(16);

exp

Category: named unary operator (numeric)

Arguments: expression

Arguments: none

Return value: numeric

Returns the natural log base (e) to the power of expression (or of $_ if none specified).

Example:

print "exp() e**1 is ",exp(1),"\n";

fcntl

Category: list operator (i/o)

Arguments: handle, function, packed_parameters

Return value:

Equivalent to the unix fnctl() call. In Perl 5 use the fntcl module, in Perl 4 there should be some mechanism for linking the perl functions to the system functions which is usually executed when Perl is installed.

fileno

Category: named unary operator (i/o)

Arguments: handle

Return value: descriptor

Returns the file descriptor given a file handle.

Example:

print("fileno() ",fileno(INF),"\n");

flock

Category: list operator (i/o)

Arguments: handle, operation

Return value: TRUE/FALSE

Calls the unix flock() function to access file locks. The handle is a Perl file handle. The operation is any valid flock() operation: place exclusive lock, place shared lock, unlock. These operations are represented by numeric values.

fork

Category: (process)

Arguments: none

Return value: pid

Calls the unix fork() function or equivalent to fork a subprocess at this point. Returns the process ID (pid) of the child process to the calling process; returns 0 to the child process itself. The calling program should wait() on any child process it forks to avoid creating zombie processes.

Example:

$pid = fork;
# Chlid only prints this
if ($pid != 0) { print("fork() Forking a process duplicates o/p: $pid \n");}
waitpid($pid,0);
# Child exits here
if ($$ != $origpid) { die; }

format

Category: list operator (i/o)

Arguments: format

Return value:

This function declares an output format specification. These formats are used in conjunction with the write() function to control the output of variables and text to conform to a standard layout structure. Normally the specification includes some variables, specifying how many characters to output and whether to justify these left, right or centered. When write() is called the actual values of the variables are used. This is useful for printing simple text reports and tables. The format specification itself is terminated by a period on a line by itself. The specification itself is in pairs of lines, the first describing the layout, and the second describing the variables to use in this layout.

Example:

format STDOUT =
format() @>>>>>>> @>>>>>>> @>>>>>>>
         $t1,     $t2,      $t3
.
$t1 = One;
$t2 = Two;
$t3 = 3;
write;

formline

Category: list operator (i/o)

Arguments: picture, list

Return value:

This function is not usually called explictly (it is an implicit part of the format mechanism). It allows direct manipulation of the format process by adding values to the format accumulator ($^A)

Example:

$tmp = formline <<'FINISH', Alpha, Beta, Gamma;
formline()  @>>>>>> @>>>>>> @>>>>>>
FINISH
print $^A;

getc

Category: named unary operator (i/o)

Arguments: handle

Arguments: none

Return value: character

This function returns the next character in specified file handle. The file defaults to STDIN if none is specified. If there are no more characters null is returned.

Example:

open INF, "/etc/motd";
print "getc() ",getc(INF),"\n";
close INF;

getgrent

Category: list operator (system files)

Arguments: none

Return value: name

Returns the next group name (or undefined) in the /etc/group system file. In a list context returns extra information taken from this file (or null list). Equivalent to the unix system call getgrent().

Example:

($name,$pw,$gid,@members)=getgrent();
print("getgrent() Examines /etc/group [$name,$gid] file.\n");

getgrgid

Category: named unary operator (system files)

Arguments: gid

Return value: name

Returns the next group name (or undefined) in the /etc/group system file with the supplied group ID (gid). In a list context returns extra information taken from this file (or null list). Equivalent to the unix system call getgrgid().

Example:

($grname,$grpw,$gid,@members) = getgrgid(0);
print("getgrgid() Returns group name given GID [$grname]\n");

getgrname

Category: named unary operator (system files)

Arguments: name

Return value: gid

Returns the next group ID, gid, (or undefined) in the /etc/group system file with the supplied group name. In a list context returns extra information taken from this file (or null list). Equivalent to the unix system call getgrname().

Example:

($grname,$grpw,$gid,@members) = getgrnam("root");
print("getgrnam() Returns group GID given name [$gid]\n");

gethostbyaddr

Category: named unary operator (system files)

Arguments: address

Return value: name

Returns the host name, (or undefined) in the /etc/hosts system file (or via a Domain Name Server lookup) with the supplied host address. In a list context returns extra information taken from this file (or null list). Equivalent to the unix system call gethostbyaddr().

Example (Perl 5 only):

use Socket;
@a=(140,203,7,103);
$addr=pack('C4',@a);
($name,$alias,$adrtype,$length,@address)=gethostbyaddr($addr,AF_INET);
print("gethostbyaddr() [$alias].\n");

gethostbyname

Category: named unary operator (system files)

Arguments: name

Return value: address

Returns the host address, (or undefined) in the /etc/hosts system file (or via a Domain Name Server lookup) with the supplied host name. In a list context returns extra information taken from this file (or null list). Equivalent to the unix system call gethostbyname().

Example:

($name,$alias,$adrtype,$length,@address)=gethostbyname("lynch");
print("gethostbyname() [$alias].\n");

gethostent

Category: (system files)

Arguments: none

Return value: name

Returns the next host name, (or undefined) in the /etc/hosts system file (or via a Domain Name Server lookup). In a list context returns extra information taken from this file (or null list). Equivalent to the unix system call gethostent().

Example:

($name,$alias,$adrtype,$length,@address)=gethostbyname("lynch");
print("gethostent() [$alias].\n");

getlogin

Category: (system files)

Arguments: none

Return value: name

Gets the current login name from the /etc/utmp system file. It is better to the the getpwuid() function for more information on the login as the information stored in /etc/utmp is limited.

Example:

print ("getlogin() ",getlogin(),"\n");

getnetbyaddr

Category: (system files)

Arguments: address

Return value: name

Returns the network name from the /etc/networks system file given a network address. In a list context returns extra information from this file. Equivalent to unix getnetbyaddr() call.

Example:

($name,$alias,$addrtype,$net) = getnetent();
($name,$alias,$addrtype,$net) = getnetbyaddr($net,$addrtype);
print("getnetbyaddr() Reads /etc/networks [$name]\n");

getnetbyname

Category: named unary operator (system files)

Arguments: name

Return value: address

Returns the network address from the /etc/networks system file given a network name. In a list context returns extra information from this file. Equivalent to unix getnetbyname() call.

Example:

($name,$alias,$addrtype,$net) = getnetbyname("localnet");
print("getnetbyname() Reads /etc/networks [$name]\n");

getnetent

Category: (system files)

Arguments: none

Return value: name

Returns the next network name from the /etc/networks system file. In a list context returns extra information from this file. Equivalent to unix getnetent() call.

Example:

($name,$alias,$addrtype,$net) = getnetent();
print("getnetent() Reads /etc/networks [$name,$addrtype]\n");

getpeername

Category: named unary operator (socket)

Arguments: socket

Return value: name

Equivalent to the unix system getpeername() system call.

getpgrp

Category: named unary operator (process)

Arguments: pid

Return value: gid

Returns the group ID (gid) of the process with the process ID (pid).

Example:

print("getpgrp() ",getpgrp(0),"\n");

getppid

Category: (process)

Arguments: none

Return value: pid

Returns the process ID (pid) if the parent process of the current process.

Example:

print("getppid() ",getppid(),"\n");

getpriority

Category: list operator (process)

Arguments: type, id

Return value: priority

Calls the unix getprority() function. The type is one of PRIO_PROCESS, PRIO_PGGRP, PRIO_USER. The id is the relevent id for this (pid, a pid for a group of processes, uid). If zero is used as the id the current process/process group/user is used.

Example:

print("getpriority() ",getpriority(0,0),"\n");

getprotobyname

Category: named unary operator (system files)

Arguments: name

Return value: protocol

Returns the protocol number from the /etc/protocols system file given the protocol name. In a list context returns extra information from this file. Equivalent to unix getprotobyname() call.

Example:

($name, $alias, $protocol) = getprotobyname("IP");
print("getprotobyname() /etc/protocols [$name,$alias,$protocol].\n");

getprotobynumber

Category: named unary operator (system files)

Arguments: protocol

Return value: name

Returns the protocol name from the /etc/protocols system file given the protocol number. In a list context returns extra information from this file. Equivalent to unix getprotobynumber() call.

Example:

($name, $alias, $protocol) = getprotobynumber(0);
print("getprotobynumber() /etc/protocols [$name,$alias,$protocol].\n");

getprotoent

Category: (system files)

Arguments: none

Return value: name

Returns the next protocol name from the /etc/protocols system file. In a list context returns extra information from this file. Equivalent to unix getprotoent() call.

Example:

($name, $alias, $protocol) = getprotoent();
print("getprotoent() Closes /etc/protocols [$name,$alias,$protocol].\n");

getpwent

Category: (system files)

Arguments: none

Return value: name

Returns the user name from the next entry in the /etc/passwd system file. In a list context returns extra information from this file. Equivalent to the unix getpwent() call.

Example:

($name,$pass,$uid,$gid,$quota,$name,$gcos,$logindir,$shell) = getpwent();
print("getpwent() /etc/passwd [$logindir,$shell].\n");

getpwnam

Category: named unary operator (system files)

Arguments: name

Return value: uid

Returns the user ID (uid) from the /etc/passwd system file given the user name. In a list context returns extra information from this file. Equivalent to the unix getpwnam() call.

Example:

($name,$pass,$uid,$gid,$quota,$name,$gcos,$logindir,$shell) = getpwnam("root");
print("getpwnam() /etc/passwd [$logindir,$shell].\n");

getpwuid

Category: named unary operator (system files)

Arguments: uid

Return value: name

Returns the user name from the /etc/passwd system file given the user ID (uid). In a list context returns extra information from this file. Equivalent to the unix getpwnam() call.

Example:

($name,$pass,$uid,$gid,$quota,$name,$gcos,$logindir,$shell) = getpwuid(0);
print("getpwuid() /etc/passwd [$logindir,$shell].\n");

getservbyname

Category: list operator (system files)

Arguments: name, protocol

Return value: port

Returns the port number of the service from the /etc/services system file given the service name and the protocol name. In a list context returns extra information from this file. Equivalent to the unix getservbyname() call.

Example:

($name,$aliases,$port,$protocol) = getservbyname("tcpmux","tcp");
print("getservbyname() /etc/servers [$name].\n");

getservbyport

Category: list operator (system files)

Arguments: port, protocol

Return value: name

Returns the service name of the service from the /etc/services system file given the port number and the protocol name. In a list context returns extra information from this file. Equivalent to the unix getservbyport() call.

Example:

($name,$aliases,$port,$protocol) = getservbyport(512,"tcp");
print("getservbyport() Problem with this! [$name]\n");

getservent

Category: (system files)

Arguments: none

Return value: name

Returns the next service name of the service from the /etc/services system file. In a list context returns extra information from this file. Equivalent to the unix getservet() call.

Example:

($name,$aliases,$port,$protocol) = getservent();
print("getservent() /etc/servers [$name].\n");

getsockname

Category: named unary operator (socket)

Arguments: socket

Return value: address

Equivalent to the unix getsockname() system call.

getsockopt

Category: list operator (socket)

Arguments: socket, level, optionname

Return value: option

Equivalent to the unix getsockopt() system call.

glob

Category: named unary operator (files)

Arguments: expression

Return value: list

Returns the list of files resulting from expanding the expression with any wildcards. This is equivalent to <*.*>.

Example:

@files = glob("/tmp/*.txt");
print "glob() ",$files[1],"\n";

gmtime

Category: named unary operator (time)

Arguments: expression

Arguments: none

Return value: list

Given a time as an argument (measured in seconds since 1st Jan 1970) returns a list of 9 elements with that time broken down. If no argument is used the current time is reported. If the system supports POSIX timezones, the time returned is localized for the Greenwich Mean Time timezone.

In a scalar context the ctime() style output is returned (a string describing the time in readable form).

Example:

($sec,$min,$hour,$mday,$mon,$year,$wday,$ydat,$isdst) = gmtime();
print "gmtime() 19$year-$mon-$mday\n";

goto

Category: (flow)

Arguments: label

Arguments: expression

Arguments: &name

Return value: n/a

The first form transfers control flow in the program to the specified label. The second allows the evaluation of an expression to supply the label name to transfer control to. The third form is a way of passing control to a subroutine from another subroutine, so that the appearance to the original caller is that the second subroutine was called directly.

Example:

print "goto ";
$count = 1;
TESTGOTO: {
   print $count, " ";
   $label = "TESTGOTO";
   if ($count < 2) {
        $count++;
     goto $label;
   }
   else {
     goto FINISH;}
}
FINISH: print "\n";

grep

Category: list operator (lists)

Arguments: expression, list

Arguments: block, list

Return value: list

This function evaluates the expression or block for each of the elements in the supplied list returning a list of the elements which were evaulated as TRUE. The most common use for this is with a pattern match operation as the expression, and a list of strings to be processed.

Example:

@a = ("One","Two","Three","Four","Five");
print("grep(), ",grep(/^T.*/,@a), "\n");

hex

Category: named unary operator (numeric)

Arguments: expression

Return value: numeric

Evaluates the expression as a hexadecimal string and returns the decimal equivalent.

Example:

print("hex() ",hex("ff"), "\n");

import

Category: list operator (scope)

Arguments: list

Return value: TRUE/FALSE

The Perl 5 module system each module has a local import() method. This is called when use() includes modules.

index

Category: list operator (string)

Arguments: string substring

Arguments: string substring position

Return value: position

Returns the position in the supplied string where the substring fisrt occurs. If a position is supplied as an argument the search begins at this element (thus repeated calls can find all occurrences if the found position is passed back as the argument to the subsequent calls). If the substring is not found the return value is -1. All array element number is based on $[ which is normally set to zero. If this value is altered it will change the way index() works as it will start its search from $[ if no position argument is supplied, and it will return $[-1 when there is no match found.

Example:

$ans1 = index("abcdefghijiklmdef:-)","def");
$ans2 = index("abcdefghijiklmdef","def",$ans1+3);
print("index() def is at $ans1 and next at $ans2\n");

int

Category: named unary operator (numeric)

Arguments: expression

Arguments: none

Return value: integer

Returns the integer part of the expression. Uses $_ as the argument if none is specified.

Example:

print("int() ",int(345.678), "\n");

ioctl

Category: list operator (files)

Arguments: handle, function, parameter

Return value: numeric

Calls the unix ioctl() function with the specified packed parameter. Returns undefined if the operating system returns -1. Returns string "0 but true" if the operating system returns 0. Otherwise returns the value returned by the operating system.

join

Category: list operator (lists)

Arguments: expression, list

Return value: string

Returns the string comprising each elemnt in the list joined with the string expression.

Example:

@listone = (0, 1, 2, 3);
print("join() ",join("-",@listone),"\n");

keys

Category: named unary operator (hash)

Arguments: array

Return value: list

Returns a list comprising each key in the associative array passed as a parameter. In a scalar context the number of keys is returned. The returned list is ordered by the internal storage requirements, so it is often useful to sort this array before processing.

Example:

%assocone = (
     One, 1,
     Two, 2,
     Three, 3,
     Four, 4
     );
print("keys() ",join("-",keys(%assocone)),"\n");

kill

Category: list operator (process)

Arguments: signal, list

Return value: TRUE/FALSE

Kills the processes with the pids in the supplied list by sending the signal level specified. If the signal level is negative the process groups are killed.

last

Category: (flow)

Arguments: label

Arguments: none

Return value: n/a

This causes control to exit the loop specified by label (or the innermost loop if none is specified).

Example:

i=1;
print("last() ");
loop: while (I<10) {
     last loop if i=3;
     print(i);
}
print("\n");

lc

Category: named unary operator (string)

Arguments: expression

Return value: string

Returns the lowercase version of any supplied expression.

Example:

print"lc() ",lc("ABCDef"), "\n";

lcfirst

Category: named unary operator (string)

Arguments: expression

Return value: string

Returns the string with the first character of the expression lowercased.

Example:

print"lcfirst() ",lcfisrt("ABCDef"), "\n";

length

Category: named unary operator (string)

Arguments: expression

Arguments: none

Return value: numeric

Returns the length of the string specified by expression. If no expression is supplied $_ is evaluated.

Example:

print("length() ",length("01234"),"\n");

link

Category: list operator (files)

Arguments: filename, linkname

Return value: numeric

Creates a new link named after the second argument linking to the filename specified in the fisrt argument. Returns 1 or 0 for success or failure.

Example:

$result = link("/usr/local",:"/tmp/link");
print("link() $result\n");

listen

Category: list operator (socket)

Arguments: socket, queuesize

Return value: TRUE/FALSE

Equivalnet to the unix listen() system call.

local

Category: named unary operator (scope)

Arguments: expression

Return value: n/a

Modifies all the variables listed to be local to the current block. The list must be enclosed in parentheses if there is more than one element. Any errors would be syntax errors. Although local() does prevent pollution of the global namespace with variables in subroutines, my() is safer than local() as it also creates new copies of the variables for each recursive call of a subroutine.

localtime

Category: named unary operator (time)

Arguments: expression

Arguments: none

Return value: list

Given a time as an argument (measured in seconds since 1st Jan 1970) returns a list of 9 elements with that time broken down. If no argument is used the current time is reported. If the system supports POSIX timezones, the time returned is localized for the current timezone.

In a scalar context the ctime() style output is returned (a string describing the time in readable form).

Example:

($sec,$min,$hour,$mday,$mon,$year,$wday,$ydat,$isdst) = localtime();
print "localtime() 19$year-$mon-$mday\n";

log

Category: named unary operator (numeric)

Arguments: expression

Arguments: none

Return value: numeric

Returns the logarithm (using the natural logarithm base e) of the expression (or of $_ if none specified).

Example:

print("log() ",log(2.5),"\n");

lstat

Category: named unary operator (files)

Arguments: handle

Arguments: expression

Return value: list

Returns the file statstics of the file pointed to by the file handle (or a file handle produced by evaluating expression). This is equivalent to stat() but if the file is a symbolic link the statistics are generated for the symbolic link itself rather than the file being linked to. Note that, like the filetest operators, lstat() can take a special argument underscore (_) which means that the test is carried out on the same filehandle as the last filetest, stat() or lstat() call.

Example:

($device,$inode,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks) = lstat("/tmp/link");
print("lstat() $device, $inode, $ctime \n");

m//

Category: named unary operator (pattern)

Arguments: m/<pattern>/<optionlist>

Arguments: /<pattern>/<optionlist>

Return value: TRUE/FALSE

Searches the default string for the pattern using regular expression pattern matching. Returns 1 (TRUE) if a match is found and '' (FALSE) otherwise. The default string can be assigned to the match using the =~ or !~ operators, otherwise it is $_.

Example:

$_ = "Happy MaN";
print "m// ",/n$/i,"\n";

map

Category: list operator (list)

Arguments: block list

Arguments: expression, list

Return value: list

Evaluates the specified expression (or block) for each indivual member of the specified list. This is done by assigning $_ to each member of the list and evaluting the expression (or block). The value returned is the list of all these results (not necessarily one perl element of the list)

Example:

@result = map($_+1,(0,1,2));
print("map() ",@result,."\n");

mkdir

Category: list operator (files)

Arguments: filename, mode

Return value: 1 or 0

Creates a directory with a name specified by the filename, with the mode specified by the octal mode. If it fails $OS_ERROR ($!) is set to operating system error.

Example:

print("mkdir() ",mkdir("/tmp/testdir",0777), "\n");

msgctl

Category: list operator (System V)

Arguments: id, cmd, arg

Return value: special

Equivalent to the unix system call msgctl() if supported.

msgget

Category: list operator (System V)

Arguments: key, flags

Return value: special

Equivalent to the unix system call msgget() if supported.

msgrcv

Category: list operator (System V)

Arguments: id, var.size, type, flags

Return value: special

Equivalent to the unix system call msgrcv() if supported.

msgsnd

Category: list operator (System V)

Arguments: id, msg, flags

Return value: special

Equivalent to the unix system call msgsnd() if supported.

my

Category: named unary operator (scope)

Arguments: expression

Return value: n/a

Declares each of the variables listed to be local() to the block. If more than one variable is specified parentheses are required. The may() specification is stronger than the the local() specification as it not only stops pollution of the global namespace, but creates a stack frame for subroutine calls so that recursive calls will behave as one would expect with local variables.

next

Category: named unary operator (flow)

Arguments: label

Arguments: none

Return value: n/a

Example:

print("next ");
@array = ("a","b","c");
loop: foreach $elem (@array) {
     next if $elem =~ /^a/;
     print $elem;
}
print "\n";

no

Category: list operator (module)

Arguments: module, list

Return value: n/a

Unimports values imported by use(), this is particularly useful when using pragmas:

Example:

use integer;
# code using integer arithmetic here
no integer;
# back to floating point arithmetic

oct

Category: named unary operator (numeric)

Arguments: expression

Return value: numeric

This function evaluates the expression as an octal string and returns the decimal value.

Example:

print("oct() ",oct("88"), "\n");

open

Category: list operator (files)

Arguments: handle, filename

Arguments: handle

Return value: TRUE (non zero) or FALSE (undefined)

This function opens a file using the specified file handle. The file handle may be an expression, the resulting value is used as the handle. If no filename is specified a variable with the same name as the file handle used (this should be a scalar variable with a string value referring to the file name).

The file name string may be prefixed with the following values to indicate the mode "<" (read, this is the default), ">" (write), "+>" (read/write - starting with new file), "+<" (read/write using existing file) , ">>" (append), "<command> |" (input pipe - the file name is actually a subshell command from which the file handle is piped), "| <command>"(output pipe - the file name is actually a subshell command to which the output of the file handle is piped). The special file name '-' refers to STDIN '-' or STDOUT '>-'.

Example:

open(FIL,"/tmp/notexist") || print("open() failed as file did not exist.\n");

opendir

Category: list operator (files)

Arguments: handle, dirname

Return value: TRUE/FALSE

Opens a directory handle for the directory name specified. If the dirname is an expression this can be evaluated to return a name.

Example:

opendir (DIR, "/tmp/notexist") || print("opendir() diled as directory dod not exist.\n");

ord

Category: named unary operator (string)

Arguments: expression

Arguments: none

Return value: numeric

Returns the numeric ascii code of the first character in the expression (or $_ if none specified).

Example:

print("ord() ",ord("A"), "\n");

pack

Category: list operator (records)

Arguments: template, list

Return value: string

Returns a packed version of the data in the list using the template to determine how it is coded. The template comprises a sequence of characters each specifying the data type of the matching data item in the list:

@Null fill to absolute position.
AAscii string with spaces to pad.
aAscii string with nulls to pad.
bBit string (ascending bit order).
BBit string (descending bit order).
cSigned char value.
CUnsigned char value.
dDouble-precision float in the native format.
fSingle-precision float in the native format.
hHex string (low nybble first).
HHex string (high nybble first).
iSigned integer value.
IUnsigned integer value.
lSigned long integer value.
LUnsigned long integer value.
nShort integer "network" order.
NLong integer "network" order.
pPointer to a null-terminated string.
PPointer to a structure (fixed-length string).
sSigned short integer value.
SUnsigned short integer value.
uUUencoded string.
vShort integer "VAX" (little-endian) order.
VLong integer "VAX" (little-endian) order.
xNull byte.
XBack up a byte.

A concise form of template can be used by appending a number after any letter to repeat that format specifier. For aA the number uses one value and pads the rest. For bB the number indicates the number of bits. For hH the number indicates the number of nybbles. For P the number indicates the size of the pointer structure. Using a * in place of a number means to repeat the format specifier as necessary to use up all list values. Note that some packed structures may not be portable across machines (in particulat network and floating point formats). It should be possible to unpack the data using the same format specification with an unpack() call.

Example:

Use Socketl
@a=(140,203,7,103);
$addr=pack('C4',@a);
($name,$alias,$adrtype,$length,@address)=gethostbyaddr($addr,AF_INET);
print("pack() ",@a, "packed as: $addr".\n");

package

Category: named unary operator (class)

Arguments: name

Return value: n/a

Calling this function declares that all unqualified dynamic variables in the current block are in the scope of the specified package name. This is normally done in the header of a file to be included as a package or a module in other programs with require() or use(). Note that this does apply to variables declared as local() but not to variables declared as my().

pipe

Category: list operator (process)

Arguments: readhandle, writehandle

Return value: TRUE/FALSE

Links named pipes like the unix function pipe().

pop

Category: name unary operator (array)

Arguments: variable

Return value: value

This function removes the top item from the array specified and returns that element.

Example:

@a = (1,2,3,4);
print("pop() ",pop(@a), "leaves ",@a,"\n");

pos

Category: named unary operator (pattern)

Arguments: variable

Return value: numeric

Returns the offset where the last pattern match (m//g) reached when searching the scalar variable specified as an argument. It can be assigned to in order to alter the bahaviour of the next match.

Example:

$name = "alpha1 alpha2 alpha3 alpha4";
$name =~ m/alpha/g;
print("pos() ", pos($name), "\n");

print

Category: list operator (i/o)

Arguments: handle, list

Arguments: list

Arguments: none

Return value: TRUE/FALSE

Prints the list to the file represented by the file handle. If no file andle is pecified the default file handle is STDOUT. This default file handle may be altered using the select() operator. If no list argument is specified $_ is printed.

Example:

$return = print "print() ";
print "returns $return on success.\n");

printf

Category: list operator (i/o)

Arguments: filehandle list

Arguments: list

Return value: TRUE/FALSE

This function uses the C printf format specifiers to control the printed output. It is equivalent to:

print filehandle, sprintf(list);
As with print() the default file handle is STDOUT.
Example:

printf("printf() An integer printed with leading zeroes %05d.\n",9);

push

Category: list operator (array)

Arguments: array, list

Return value: numeric

This appends the elements in the specified list on the end of the specified array and returns the new number of elements in the list.

Example:

@a = (1);
$num = push(@a,2,3,4,5);
print("push() Added ",$num-1," elements to array: ",@a,"\n");

q/STRING/

Category: (string)

Arguments: q/string/

Return value: value

This is a standard quote, used to surpress special interpretation of characters giving a literal string. One can use single quotes 'string' or the letter q with delimiters. Any delimiter will do as long as it is not used in the string. The backslash character can be used to escape any reference to the delimiting character itself in the string.

Example:

print(q!q// The only special character is the delimiter itself \!!, "\n");

qq/STRING/

Category: (string)

Arguments: qq/string/

Return value: value

This is a double quote, used to allow interpolation of special characters within the string as required. One case use double quote ""string" or the double letter qq with delimiters. The backslash character can be used to disable the special meaning of interpolated characters, including the delimiter itself.

Example:

$newline = "\n";
print(qq!qq// This is a normal double quoted string with interpolation! $newline!);

quotemeta

Category: named unary operator (pattern)

Arguments: expression

Return value: string

Returns the value of the expression with all the metacharacters backslashed.

Example:

print(quotemeta("quotameta() I can use any metcharacter $ \ "),"\n");

qw/STRING/

Category: (list)

Arguments: qw/string/

Return value: list

Returns a list of words in string. Spaces are used as delimiters in the string to produce this list.

Example:

print("qw// ",qw("1 2 3 4 5"),"\n");

qx/STRING/

Category: (process)

Arguments: qx/string/

Return value: special

This is a back quote, used to allow interpolation of special characters within the string as required, and then execute the resulting command as a system command. One can use back quotes `string` or the letters qx with delimiters. The backslash character can be used to disable the special meaning of interpolated characters, including the delimiter itself. The return value is the return value of the system() call.

Example:

print("qx// ",qx!du -s /tmp!);

rand

Category: named unary operator (numeric)

Arguments: expression

Arguments: none

Return value: numeric

This function returns a real number between 0 and the number evaluated as expression (the upper limit is 1 is no expression is specified). The upper limit must be positive. As the function calls a pseudo random generator, it should be possible to generate the same sequence of numbers repeatedly unless the initial seed value is altered with srand().

Example:

print("rand(), ",rand,"\n");

read

Category: list operator (i/o)

Arguments: handle, variable, length, offset

Arguments: handle, variable, length

Return value: TRUE/FALSE

Reads length bytes from file handle into variable (starting at offset if specified). Returns number of bytes actually read.

Example:

open(INF,"/etc/services") || die "Error reading file, stopped";
read(INF,$result,10);
print("read() $result \n");
close(INF)

readdir

Category: list operator (i/o)

Arguments: dirhandle

Return value: lname

In a lsit context returns a list of the files in the directory specified by the directory handle. In a scalar context returns the next file name in the directory.

Example:

opendir(DIR,"/tmp");
@file = readdir(DIR);
print("readdir() ",@files, "\n");

readlink

Category: named unary operator (files)

Arguments: expression

Arguments: none

Return value: value

Returns the value of the symbolic link specified by expression (or $_ if none specified). If symbolic links are not implemented gives a fatal error. If symbolic links are supported, but there is some system error, this is returned in $OS_ERROR ($!).

recv

Category: list operator (socket)

Arguments: socket, variale, length, flags

Return value: address

Equivalent to unix system call recv().

redo

Category: (flow)

Arguments: label

Arguments: none

Return value: n/a

Passes control directly to the label without executing any contine block. If no label is specified the innermost loop is used.

ref

Category: named unary operator (class)

Arguments: expression

Return value: package

Returns the package of a bless()ed variable. Otherwise returns TRUE if the variable is a reference and FALSE otherwise. The return value for TRUE is actually the type of the variable (for example ARRAY, HASH, REF, SCALAR).

Example:

$tmp = {};
bless $tmp, ATMPCLASS;
print "ref() \$tmp is now in class ",ref($tmp),"\n";

rename

Category: list operator (files)

Arguments: oldname, newname

Return value: 1 (true) 0 (fail)

Renames files on the same file system from oldname to new name.

Example:

$returned = rename("/tmp/test","/tmp/test2");
print("rename() returned $returned \n");

require

Category: named unary operator (module)

Arguments: expression

Arguments: none

Return value: TRUE/FALSE

If the expression is a scalar the library specified by the filename is included (if it has not already been).

In Perl 5 if the expression is numeric this requires that the version if Perl being used (in $PERL_VERSION, $[) is greater than or equal to the version specified.

Note that Perl 5 also has the use() mechanism for including modules which is more robust.

Example:

require "cgilib.pl";

reset

Category: named unary operator (misc)

Arguments: expression

Arguments: none

Return value: 1

This a way of resetting variables in the current package (especially pattern match variables). The expression is interpreted a a list of single characters. All variables starting with those characters are reset. The letters are case sensitive (as Perl variables are). Hyphens may be used to specify ranges of variables to reset. If called without any argument it simply resets all search matches.


Use of this operator can reset system variables you may not want to alter. Be very careful with the following for example:

reset A-Z;

return

Category: list operator (flow)

Arguments: list

Return value: list

This function returns from a subroutine (or an eval()) with the value specified.

Example:

sub test {
     return 1;
}
$test = &test;
print("return() Returned $test \n");

reverse

Category: list operator (list)

Arguments: list

Return value: list

Returns the list given as an argument in reverse order. In a scalar context it reverses the letters of it's first argument.

Example:

@a = (1,2,3);
print("reverse() ",reverse(@a),"\n");

rewinddir

Category: named unary operator (i/o)

Arguments: dirhandle

Return value: TRUE/FALSE

When reading a directory using readdir() it is possible to reset the directory to the first file name using rewindddir().

Example:

opendir(DIR,"/tmp");
print("rewinddir() (a): "
file: while ($file=readdir(DIR) {
     print $file, " ";
}
rewinddir();
print(" (b): "
file: while ($file=readdir(DIR) {
     print $file, " ";
}
print("\n");
closedir(DIR);

rindex

Category: list operator (string)

Arguments: string, subsitring, position

Arguments: string, subsitring

Return value: position

This function is very similar to index() except that, instead of scanning for the substring from the first character in the string, it scans backwards from the last character. So it returns the starting position of the last occurance of substring in string (starting at position if specified but scanning backwards from there).

Example:

$ans1 = rindex("abcdefghijiklmdef:-)","def");
$ans2 = rindex("abcdefghijiklmdef","def",$ans1+3);
print("rindex() def is at $ans1 and next at $ans2\n");

rmdir

Category: named unary operator (files)

Arguments: filename

Return value: 1 or 0

Deletes the directory specified (or $_) if it is empty. Sets $OS_ERROR ($!) on system error.

s///

Category: (pattern)

Arguments: s/pattern/replacement/options

Return value: numeric

Searches the default string for pattern (a regular expression) and replaces this with the replacement string (the actual replacemnt behaviour depends on the options). It returns the number of replacements made. The default string is set using either of the pattern binding operators (=~ or ¬~ ) or $_ is used if none have been bound. The valid options are:

eEvaluate the right side as an expression
gGlobal (replace all occurrences)
iCase-insensitive pattern matching
mIgnore \n in string (multiple lines)
oOptimize (compile pattern once)
sTreat string as single line
xExtended regular expressions

See also the Special Variables $<n> which can be used in the replacement string to replace with certain parts of the pattern matched.

Example:

$oldstr = "abcdefABCDEFabcdefABCDEF";
$newstr= $oldstr;
$str =~ s/abc/zzz/ig;
print("s/// $oldstr became $newstr \n");

scalar

Category: named unary operator (misc)

Arguments: expression

Return value: value

This operator forces the argument to interpreted in a scalar context, rather than as a list, so that it can override the default context if necessary.

seek

Category: list operator (i/o)

Arguments: handle, position, start

Return value: TRUE/FALSE

This function sets the file pointer to a specified offset position in a file. The offset is relative to the start which can have three values: 0 (start of file), 1 (current position), 2 (end of file). This allows the use of random access files, and the implentation of fast read algorithms (for example binary search techniques) on file handles, especially with fixed length data where the offsets are easier to calculate.

seekdir

Category: list operator (i/o)

Arguments: dirhandle. position

Return value: TRUE/FALSE

This function allows the position in a directory to be reset to a position saved with telldir(). This is useful when processing directories with readdir().

select

Category: named unary operator (i/o)

Arguments: handle

Arguments: rbits, wbits, ebits, timeout

Return value: handle

This operator selects the default file handle used for input/ouput operations such as print() and write(). By default STDOUT is selected, but this function can select any other file handle to be the default instead. The return value is the currently selected file handle (before any change) so it is useful to assign this to a variable in order to be able to restore the original handle as the default at a later stage.

The second form calls the unix system select() function.

Example:

open(OUT,"/tmp/t.out");
$return = select(OUT);
print("This goues in /tmp/t.out.\n");
select($return);
print("select() restored to STDOUT.\n");

semctl

Category: list operator (System V)

Arguments: id, semnum, command, arg

Return value: value

Equivalent to the unix semctl() function.

semget

Category: list operator (System V)

Arguments: key, nsems, flags

Return value: value

Equivalent to the unix semget() function.

semop

Category: list operator (System V)

Arguments: key,. opstring

Return value: TRUE/FALSE

Equivalent to the unix semop() function calle.

send

Category: list operator (socket)

Arguments: socket, message, flags, to

Arguments: socket, message, flags

Return value: numeric

Equivalent to the unix system send() function.

setgrent

Category: (system files)

Arguments: none

Return value: n/a

Rewinds the /etc/group file to the start of the file for subsequent accesses using getgrent().

Example:

print("setgrent() ",setgrent(), "\n");

sethostent

Category: named unary operator (system files)

Arguments: flag

Return value: n/a

If called with an argument of 1 tells the system to keep a TCP socket open for name server queries such as gethostbyname(). If this is not then then name server queries use UDP datagrams.

Example:

print("sethostent() ",sethostent(1), "\n");

setnetent

Category: named unary operator (system files)

Arguments: flag

Return value: n/a

Rewinds the /etc/networks file used by getnetent() and other network related functions. If the flag has a value of 1 then the file is kept open between calls to getnetbyname() and getnetbyaddr().

print("setnetent() ",setnetent(1), "\n");

setpgrp

Category: list operator (process)

Arguments: pid, pgrp

Return value: TRUE/FALSE

This function sets the current process group for the specified process (pid), if this is zero the current process is set.

setpriority

Category: list operator (proxess)

Arguments: type, id, priority

Return value: TRE/FALSE

Calls the unix setprority() function. The type is one of PRIO_PROCESS, PRIO_PGGRP, PRIO_USER. The id is the relevent id for this (pid, a pid for a group of processes, uid). If zero is used as the id the current process/process group/user is used. The priority is a number representing the level of priority (normally in the range 120 to 20) where the lower the priority the more favourable the scheduling of the process by the operating system.

Example:

print("setpriority() ",setpriority(0,0,-20),"\n");

setprotoent

Category: named unary operator (system files)

Arguments: flag

Return value: TRUE/FALSE

Rewinds the /etc/protocols file used by getprotoent() and other protocol related functions. If the flag has a value of 1 then the file is kept open between calls to getprotobyname() and getnetbynumber().

Example:

print("setprotoent() ",setprotoent(1), "\n");

setpwent

Category: (system files)

Arguments: none

Return value: TRUE/FALSE

Rewinds the /etc/passwd file used by getpwent() and other password related functions.

Example:

print("setpwent() ",setpwent(), "\n");

setservent

Category: named uanry operator (system files)

Arguments: flag

Return value: TRUE/FALSE

Rewinds the /etc/services file used by getservent() and other service related functions. If the flag has a value of 1 then the file is kept open between calls to getservbyname() and getnetbyport().

Example:

print("setservent() ",setservent(1), "\n");

setsockopt

Category: list operator (socket)

Arguments: socket, level, optname, optval

Return value: TRUE/FALSE

Equivalent to unix system call setsockopt().

shift

Category: named unary operator (array)

Arguments: array

Arguments: none

Return value: value

This functions takes the leftmost element from the array specified and returns that, reducing the array by one element. If no array is specified, the array of arguments passed to the Perl script, $ARGV, is used if the context is not in a subroutine, otherwise the array of arguments passed to the subroutine, @_, is used.

The return value is undefined if the array is empty.

Example:

print("shift() ");
while ($arg = shift) {
     print($arg,' ');
}
print("\n");

shmctl

Category: list operator (System V)

Arguments: id, cmd, arg

Return value: value

Equivalent to the unix shmctl() function.

shmget

Category: list operator (System V)

Arguments: key. size, flags

Return value: value

Equivalent to the unix shmget() function.

shmread

Category: list operator (System V)

Arguments: id, var. pos, size

Return value: value

Equivalent to the unix shmread() function.

shmwrite

Category: list operator (System V)

Arguments: id, string, pos, size

Return value: value

Equivalent to the unix shmwrite() function.

shutdown

Category: list operator (socket)

Arguments: socket, how

Return value: TRUE/FALSE

Equivalent to the unix shutdown() function.

sin

Category: named unary operator (numeric)

Arguments: expression

Arguments: none

Return value: numeric

Returns the sine of the expression in radians. If there is no explicit argument $_ is used.

Example:

print("sin() ",sin(4), "\n");

sleep

Category: named unary operator (process)

Arguments: expression

Arguments: none

Return value: numeric

Causes the current process to sleep for the number of seconds specified in expression (if none specified it sleeps forever, but may be woken up by a signal if this has been programmed).

Example:

print("sleep() ",sleep(5),"\n");

socket

Category: list operator (socket)

Arguments: socket, domain, type, protocol

Return value: value

Equivalent to the unix socket() system call.

socketpair

Category: list operator (socket)

Arguments: socket1, socket2, domain, type, protocol

Return value: value

Equivalent to the unix socketpair() system call.

sort

Category: list operator (list)

Arguments: subname list

Arguments: block list

Arguments: list

Return value: list

This function sorts the list specified and returns the sorted list. The sort method can be specified with the optional subroutine or block argument. A subroutine may be specified which takes two arguments (passed as global package variables $a $b) and returns true if the first is less that or equal to the second by any sort criteria used. Similarly a block can be specified (effectively an anonymous subroutine) to perform this function. The deafult sort order is based on the standard string comparison order.

Example:

@a = ("z","w","r","i","b","a");
print("sort() ",sort(@a),"\n");

splice

Category: list operator (array)

Arguments: array, offset, length, list

Arguments: array, offset, length

Arguments: array, offset

Return value: list

Removes the elements specified by offset and length from the array replacing them with the elements in the list supplied as the last argument. Alist of those elements removed is returned. If no length is specified all the items from offset to the end of the array are removed.

Example:

@a = ("a","e","i","o","u");
print("splice() ",splice(@a,0,3,"A","E","I"),"\n");

split

Category: list operator (pattern)

Arguments: /pattern/,expression,limit

Arguments: /pattern/,expression

Arguments: /pattern/

Arguments: none

Return value: list

This function manipulates a string, splitting the srting denoted by the expression (or the $_ if none is specified) into an array of strings based on some separator string specified by the pattern (if the pattern is no specified whitespace is the default). An optional limit restricts the number of elements returned. A negative limit has no effect, no limit is imposed.

If not in a list context the number of elements found is returned. In an scalar context returns the number of elements and puts the resulting array into the @_ array (the use of the @_ as the result is depreciated).

Examples:

print("spilt() ",split(/:/,"1:2:3:4:5"),"\n");

sprintf

Category: list operator (string)

Arguments: format, list

Return value: string

This is equivalent to the C sprintf() call. The format is a string with special metacharacters to specify how may values/variables follow and how to represent each of these in the resulting string. This allows for the explicit formatting of flotaing point and integer numbers (also allowing binary, hex and octal formats).

Example:

print("strintf() ",sprintf("%0d \n",9),"\n");

sqrt

Category: named unary operator (numeric)

Arguments: expression

Return value: numeric

Returns the result of evaluating the expression and finding its square root.

Example:

print("sqrt() ",sqrt(4),"\n");

srand

Category: named unary operator (numeric)

Arguments: expression

Arguments: none

Return value: TRUE/FALSE

This functions sets the seed used by the pseudo random number generation algorithm when generating rand() numbers. In order to randomize the possible sequences the seed should be set to a different vale each time the script is called. The default behaviour, when no expression is supplied, is to use the result of a call to time(). This is not a secure method of randomizing for scripts which need to be secure as it is possible to predict what sequence the script will return.

Note that, when using a set of pseudo random data generated using rand(), it is possible to generate exactly the same data repeatedly (without having to save the entire sequence) simply by stetting and saving the seed. Restoring the seed and calling rand() will then produce the same sequence again.

Example:

srand(26);
print("rand() ",rand(),", ");
srand(26);
print(rand()," (should produce the same \"random\" number twice) \n");

stat

Category: list operator (files)

Arguments: handle

Arguments: expression

Arguments: none

Return value: list

Returns the file statistics of the file pointed to by the file handle (or a file handle produced by evaluating expression). Note that, like the filetest operators, stat() can take a special argument underscore (_) which means that the test is carried out on the same filehandle as the last filetest, stat() or lstat() call.

Example:

($device,$inode,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks) = stat("/etc/passwd");
print("stat() $device, $inode, $ctime \n");

study

Category: named unary operator (pattern)

Arguments: scalar

Arguments: none

Return value: TRUE/FALSE

When many pattern match operations are being performed on the same string, the efficiency of these patterns can be improved by the use of the study() function. If no string is sepcified the $_ is studied by default. The call sets up internal lookup tables based on the string studied so that pattern matching operations can use this information to processs the pattern match more quickly. Only one string at a time can be studied (subsequent calls effectively "unstudy" any previous study()). The function study() is often used in a loop processing lines of a text file where each line is studied before being processed with various pattern matches.

sub

Category: (flow)

Arguments: name block

Arguments: name

Arguments: name

Return value: value

This is the syntax for a subroutine declaration. The full form defines a subroutine with the name and associates this with the statements in block. When envoked it will retun the result of the last ststement executed in the block (often a return() statement). If no name is supplied it is an anonymous subroutine (certain functions such as sort() allow anonymous subroutines as arguments). With only a name as an argument, the statement is a forward reference to a subroutine which is decalred fully later in the script.

substr

Category: list operator (string)

Arguments: expression, offset, length

Arguments: expression, offset

Return value: string

Returns a substring of a string specified by expression. The substring starts at the specified offset and has the specified length. If the offset is negative it starts from the right hand side of the string instead of the left hand side. If the length is negative, it means to trim the string by that number of characters.

Example:

print("substr() ",substring("okay",0,2),"\n");

symlink

Category: list operator ((files)

Arguments: oldfile, newfile

Return value: 1 or 0

This functions creates a symbolic link from the existing file specified by oldfile to the specified newfile. Returns 1 on success, and 0 on failure. If symbolic links are not supported by the operating system this will return a fatal error.

Example:

print("symlink() ",symlink("/usr/local","/tmp/symlinktousrlocal"),"\n");

syscall

Category: list operator (i/o)

Arguments: list

Return value: varies

This mechanism allows Perl to call corresponding unix C system calls directly. It relies on the existence of the set of Perl header files syscall.ph which declare all these calls. The script h2ph which is normally executed when Perl is installed sets up the syscall.ph files. Each call has the same name as the equivalent unix system call with the "SYS_" prefix. As these calls actually pass control to the relevant C system function care must be taken with passing parameters.

The fisrt element in the list used as an argument to syscall() itself is the name corresponding to the unix system call (i.e. with the "SYS_" prefix). The next elements in the list are interpreted as parameters to this call. Numeric values are passed as the C type int. String values are passed as pointers to arrays. The length of these strings must be able to cope with any value assigned to that parameter in the call.

Example:

require "syscall.ph";
print("syscall() ",syscall(&SYS_getpid)," equivalent to $PID\n");

sysopen

Category: list operator (i/o)

Arguments: handle, name, mode, permissions

Arguments: handle, name, mode

Return value: TRUE/FALSE

This function calls the unix C open() function directly from the Perl script.

sysread

Category: list operator (i/o)

Arguments: handle, scalar, length, offset

Arguments: handle, scalar, length

Return value: TRUE/FALSE

This function calls the unix C read() function directly from the Perl script.

system

Category: list operator (process)

Arguments: list

Return value: status

This call is executes the specified list as an operating system call. The process to execute this command is forked and the script waits for the child process to return. The return value is the exit status of the child process.


To capture the output from a system call use the qx// (back quote mechanism) rather than system().

Example:

print("system() ",system("ls -F /var > /tmp/t.tmp"),"\n");

syswrite

Category: list operator (i/o)

Arguments: handle, scalar, length, offset

Arguments: handle, scalar, length

Return value: TRUE/FALSE

This function calls the unix C write() function directly from the Perl script.

tell

Category: named unary operator (i/o)

Arguments: expression

Arguments: none

Return value: position

This function returns the current position in the file specified by the expression (which should evaluate to a filehandle). If no handle is specified, that last file accessed is used. This value can be used by seek() to return to this position if appropriate.

Example:

print("tell() ",tell(STDOUT),"\n");

telldir

Category: named unary operator (i/o)

Arguments: dirhandle

Return value: position

This function returns the current position in the directory handle specified. This value can be used by seekdir() to return to this position if appropriate.

Example:

opendir(DIR,"/tmp");
readdir(DIR);
print("telldir() ",telldir(DIR),"\n");

tie

Category: list operator (class)

Arguments: variable, classname, list

Return value: object

This functions binds a variable to a package class. The creates an instance of this class by running the new() method associated with that class. Any parameters for the new() method may be specified in the list.

The behaviour depends on the way the package class is written, and on the type of variable. Most common are package classes written to support associative arrays. In particular package classes exist to bind associative arrays to various databases.

The tie() mechanism has the effect of hiding all the complexities of implemention behind a simple interface, so that, for example, the records in a database can be accessed by looking at the associative array bound to the database though an appropriate package class.

The example here uses the Configure.pm module. This module stores the information about the machine on which Perl has been installed. It is possible to bind an associateive array to this class and examine this to find out the value of any of the configuration parameters.

Example:

use Configure;
$return = tie %c, Configure;
print("tie() returned \"$return\" and a sample value is $c{installbin}\n");

tied

Category: named unary operator

Arguments: variable

Return value: object


This was first implemented in Perl 5.002

This function returns a reference to the object which the variable is an instance of. This is same as was returned by the original call to tie() when it was bound.

time

Category: (time)

Arguments: none

Return value: time

Returns the time in seconds since the 1st January 1970. The format can be converted into more useful parts using gmtime() or localtime().

times

Category: (process)

Arguments: none

Return value: list

This function returns a list of four elements representing the time in seconds used. The four elements represent the system time and the user time used by the current process, and child processes.

Example:

($usertime,$systemtime,$childsystem,$childuser) = times();
print("times() $usertime $systemtime $childsystem $childuser\n");

tr///

Category: (string)

Arguments: tr/searchlist/replacelist/<options>

Return value: numeric

This function translates all occurrances of items in the search list with the equivalent items in the replacement list. The srting searched is the default search string bound by =~ or !=, or if no string is bound to the pattern match, the $_ string is used. The return value is the number of characters translated or deleted.

The valid options are:

cComplement (non-matching characters in search list are used)
dDelete (delete any characters not in search list as well as translating)
sSquash (if the trasnslation results in a sequence of repeated characters from the replace list then reduce this to one occurance of the character).
The search list and the replace list may contain the - character to indicate a range of characters.

Examples:

tr/AEIOU/aeiou/     # Make all vowels lowercase
tr/[A-M]/[a-m]/     # Make first half of alphabet lowercase
tr/aeiou/ /c          # Replace all non-vowles with space
tr/aeiou/AEIOU/d     # Make all vowels uppercase and remove all other characters
tr/aeiou/-/s          # Replace all vowels with -, but only one - for adjacent vowles

truncate

Category: list operator (i/o)

Arguments: handle, length

Arguments: expression, length

Return value: TRUE/FALSE

Truncates the file referenced by the file handle to length. An expression can be used which evaluates to the file handle. If the operating system does not implement this feature.

uc

Category: named unary operator (string)

Arguments: expression

Return value: string

Returns an uppercase version of the specified expression.

Example:

print("uc() ",uc("This is All Caps"), "\n");

ucfirst

Category: named unary operator (string)

Arguments: expression

Return value: string

Returns a string with the first character of the expression in uppercase.

Example:

print("ucfirst() ",ucfirst("this is Capitalized"), "\n");

umask

Category: named unary operator (files)

Arguments: newumask

Arguments: none

Return value: oldumask

Sets the file mask using the specified newumask. Returns the oldumask so that it can be stored and restored later if required. If called without any arguments returns the current umask. This is the mechanism unix uses to modify the permissions of any files created.

Example:

print("umask() The current umask is: ",umask,"\n");

undef

Category: named unary operator (misc)

Arguments: expression

Arguments: none

Return value: value

Undefines the value of the expression. The expression may be a scalar value, and array or a subroutine (specified with a & prefix). When called without an expression returns an undefined value.

unlink

Category: list operator (files)

Arguments: list

Return value: numeric

Deletes the files in the list and returns the number of files deleted.

Example:

system("touch /tmp/t.tst");
print("unlink() ",unlink("/tmp/t.tst"),"\n");

unpack

Category: list operator (data)

Arguments: template, expression

Return value: list

This functions unpacks data that are packed with pack(). It uses the same template mechanism to specify the format of the data in the packed string. In a scalar context the fisrt value in the list is returned.

unshift

Category: list operator (array)

Arguments: array, list

Return value: numeric

Prepends the list to the front of the specified array. Returns the new number of elements in array.

Example:

@a = (a, b, c);
$ret = unshift(@a, 1, 2, 3);
print("unshift() Array has $ret elements:",@a,"\n");

untie

Category: named unary operator (class)

Arguments: variable

Return value: TRUE/FALSE

Undoes the bining between a variable and a package class which was created using tie().

use

Category: list operator (module)

Arguments: module, list

Return value: n/a

Imports the specified module into the current block. The import() method defined for the package class represented by the module is evaluated. The specified list is passed as optional arguments to this import() method. If you do not specify a list argument then the default methods for that module will be those imported. You can specify the emty list () in order to avoid adding any items to the local namespace.

Example:

use English;
Note that this is the mechanism for implementing compiler directives known as pragmas. You can for example force all aritmateic to be interger based by:

use integer; 
And then this can be turned off again with:

no integer;

utime

Category: list operator (files)

Arguments: list

Return value: numeric

This function sets the access and modification time of all the files in the list to the time specified in the first item two items in the list. The time must be in the numeric format (i.e. seconds since 1st Januray 1970) as returned by the time() function.

Example:

$time = now;
print("utime() ",utime($time,$time,"/tmp/t.tst"),"\n");

values

Category: named unary operator (hash)

Arguments: variable

Return value: list

This function retuns the array comprising all the values in the associate array specified. In a scalar context returns the number of values in the array.

Example:

%a = (1, "one", 2, "two", 3, "three");
print("vaules() ",values(%a),"\n);

vec

Category: list operator (fixed)

Arguments: expression, offset, bits

Return value: value

This function uses the string specified by expression as a vector of unsigned integers. The return value is the value of the bitfield specified by offset. The specified bits is the number of bits that are reserved for each entry in the bit vector. This must be a power of two from 1 to 32. Note that the offset is the marker for the end of the vector, and it counts back the number of bits specified to find the start.

Vectors can be manipulated with the logical bitwise operators |, & and ^.

Example:

$vec = '';
vec($vec,3,4) = 1;     # bits 0 to 3
vec($vec,7,4) = 10;     # bits 4 to 7
vec($vec,11,4) = 3;     # bits 8 to 11
vec($vec,15,4) = 15;     # bits 12 to 15
# As there are 4 bits per number this can be decoded by unpack() as a hex number
print("vec() Has a created a string of nybbles, in hex: ",unpack("h*",$vec),"\n");

wait

Category: (process)

Arguments: none

Return value: pid

Waits for a child process to exit. Returns the process ID (pid) of the terminated process, and -1 if there are no child processes.

waitpid

Category: list operator (process)

Arguments: pid, flags

Return value: pid

Waits for a specified child process to exit and returns pid of the terminated process, and -1 if there is no child process matching the pid specified. The flags can be set to variuos values which are equivalent to the waitpid() unix system call (if the opertating system supports this), a flags value of 0 should work on all operating systems supporting processes.

wantarray

Category: (flow)

Arguments: none

Return value: TRUE/FALSE

This function returns TRUE if the current context is an array context, otherwise returns FALSE. This construct is most often used to return two alternatives from a subroutine, depending on the calling context:

Example:

return wantarray ? (8, 4, 33) : 3;

warn

Category: list operator (i/o)

Arguments: list

Return value: TRUE/FALSE

Prints the supplied list to STDERR, like die() if there is no newline in the list warn() will append the text "at line <line number>\n" to the message. However, the script will contiinue after a warn().

write

Category: list operator (i/o)

Arguments: expression

Arguments: handle

Arguments: none

Return value:

Writes a formatted record to the file handle (or the file handle whicg the expression evaluates to). If no file handle is specified, the default is STDOUT, but this can be altered using select() if necessary.

A format for use by that file handle must have been declared using the format() function. This defaults to the name of the file handle being used, but other format names can be associated with the current write() operation by using the $FORMAT_NAME ($~) special variable.

y///

Category: (string)

Arguments: y/searchlist/replacelist/<options>

Return value: numeric

The operator y/// is a synonym for the translation operator tr///.

From Here

This chapter only lists Perl special functions. It makes sense to consult the other two reference sections for Perl special variables and Perl operators. In particular, the chapter on Operators explains the precedence of functions in relation to other operations in more detail.


Copyright © 1996, Que Corporation
Technical support for our books and software is available by email from
support@mcp.com

Copyright ©1996, Que Corporation. All rights reserved. No part of this book may be used or reproduced in any form or by any means, or stored in a database or retrieval system without prior written permission of the publisher except in the case of brief quotations embodied in critical articles and reviews. Making copies of any part of this book for any purpose other than your own personal use is a violation of United States copyright laws. For information, address Que Corporation, 201 West 103rd Street, Indianapolis, IN 46290.

Notice: This material is from Special Edition, Using Perl for Web Programming, ISBN: 0-7897-0659-8. The electronic version of this material has not been through the final proof reading stage that the book goes through before being published in printed form. Some errors may exist here that are corrected before the book is published. This material is provided "as is" without any warranty of any kind.

[Copyright Information] [Table of Contents] [Que Home Page]
[Prev Chapter] [Next Chapter]