Appendix C

Function List


CONTENTS

Perl has a large number of functions and an even wider range of additional modules each with its own additional functions. This appendix lists all the standard functions alphabetically for reference.

Each function has been assigned one or more categories to aid you in finding the function that you need. This is a very rough categorization, as many functions might overlap in any category scheme.

For each function, the needed parameters are shown. The parameters are described in the text where the meaning is not obvious.

Quite a few of Perl's function mirror those available to C programmers under the UNIX system and are at least moderately complicated to use. Please look in the UNIX documentation for additional information if you're interested in the socket, shared memory, or semaphore functions.

Functions by Category

This section listed Perl's functions by category.

Functions by Name

Here is the list of Perl's function sorted by name.

abs([EXPR])

Category: Math
Return Value: scalar, the absolute value of EXPR or $_ if no expression is specified.
Definition: Calculates an absolute value. For example, abs(-10) is 10.

accept (NEWSOCKET, GENERICSOCKET)

Category: Socket
Return Value: SCALAR, the packed address of the client or false if a problem occurred.
Definition: Accepts a socket connection from clients waiting for a connection. The GENERICSOCKET parameter must have already been opened using the socket() function. You can find more information about accept() in section 2 of the UNIX manual pages.

alarm (NUM_OF_SECONDS)

Category: Process
Return Value: SCALAR, the number of seconds remaining before the previous alarm was due to go off.
Definition: Sends a SIGALARM to your script after NUM_OF_SECONDS. A call with NUM_OF_SECONDS equal to zero cancels the current alarm. You can find more information about alarm() in section 3 of the UNIX manual pages. It is poss-ible for Perl to trap such signals and call specific signal handling subroutines. See Chapter 13, "Handling Errors and Signals."


alarm(10);

atan2 ([EXPR])

Category: Math
Return Value: SCALAR, the arc tangent of EXPR or of $_ if no expression is specified.
Definition: Calculates an arc tangent.


$arcTangent = atan2(60,2);

bind (SOCKET, NAME)

Category: Socket
Return Value: SCALAR, the socket handle or false if an error occurred.
Definition: Binds a network address to the socket handle. You can find more information about bind() in section 2 of the UNIX manual pages.

binmode (FILEHANDLE)

Category: File
Return Value: SCALAR, true if successful or undefined if not.
Definition: On systems which distinguish between text and binary files (like Windows 95 and Windows NT) this function forces binary mode treatment of FILEHANDLE. In systems which do make the distinction, text files have the end of line characters-carriage return ('\r') and linefeed('\n')-automatically translated into the UNIX end-of-line character ('\n') when reading from the file and when writing to the file. Binary mode files do not have this automatic transformation. See "Example: Binary Files" in Chapter 9 "Using Files," for more information.


open(FILE, "file.dat");

binmode(FILE);

bless (REFEREncE, [CLASSNAME])

Category: Object
Return Value: SCALAR, a reference to the blessed object.
Definition: Changes the type of the referenced variable to CLASSNAME. It is used to assign a class name to the referenced variable, thus changing the string returned by the ref() function. If CLASSNAME is not specified, the name of the current package is used. See Chapter 8, "References," for more information.


$temp = { }

bless $temp, 'ATMPCLASS';

print("bless() \$temp is now has type ", ref($temp), "\n");


Tip
Always specify the CLASSNAME parameter if the blessing function might be inherited.

caller ([EXPR])

Category: Scope
Return Value: in Scalar Context: SCALAR, true if the current code has been called as a subroutine (this includes code which is included using a require() or an eval() call). Otherwise, false.
Return Value in Array Context: ARRAY, contains details of the calling context comprising the package name, file name, and line of the call.
Definition: This function is used to test the current scope of a subroutine call.


sub testcaller {

    ($package, $file, $line) = caller;

print("caller() Package=$package File=$file Line=$line\n");

}

testcaller();

chdir ([DIRNAME])

Category: Directory
Return Value: SCALAR, true if successful, false otherwise.
Definition: Changes the current directory to the directory specified. If no argument is given changes to the home directory of the current user.


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

chmod (MODE, LIST)

Category: File, UNIX
Return Value: SCALAR, the number of files changed.
Definition: MODE is an octal number representing file permissions which are applied to all the files in LIST.


chmod(0744, "test1.txt", "test2.txt");

chomp ([STRING | LIST])

Category: Array, String
Return Value: SCALAR, the number of characters removed.
Definition: This is a safer alternative than the chop() function for removing characters at the end of strings. Chomp() only removes characters that correspond to the value of $/ (the input line separator). It can be given a list of strings upon which to perform this operation. When given no arguments the chomp operation is performed on $_.


$temp = "AAAAA!\n";

print("chomp(\$temp) returned ", chomp($temp), ".\n");

chop ([STRING | LIST])

Category: Array, String
Return Value: SCALAR, the last character that was removed.
Definition: This function removes the last character of STRING or the last character of each element in LIST.


$tmp = "1234";

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


Tip
Use chomp() (with $/ set to "\n") rather than chop() if you are not sure that the string has a trailing newline.

chown (NUMERICAL_UID, NUMERICAL_GID, LIST)

Category: File, UNIX
Return Value: SCALAR, the number of files successfully changed.
Definition: Changes the ownership of the files in LIST to the user ID and the group ID specified as parameters.


chown(1, 1, "test1.txt");

chr (NUMBER)

Category: String
Return Value: SCALAR, the character represented by NUMBER.
Definition: Returns the ASCII character represented by NUMBER. For example, chr(69) is the letter E. See Appendix E, "ASCII Table" for more information.

chroot (DIR_NAME)

Category: File, UNIX
Return Value: SCALAR, true if successful, false otherwise.
Definition: Changes the root directory of the current process to DIR_NAME. Which means that a filename like /john.dat might really refer to /root/users/~jmiller/john.dat.


chroot("/usr/~waters");

Tip
Your process must have superuser rights in order to successfully use this function. It is used to make processes safer by only allowing them access to the subdirectory tree relevant to their purpose.

close (FILEHANDLE)

Category: File
Return Value: SCALAR, true if the file was closed correctly, false if not.
Definition: Closes the file opened with 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.


open(FILE, "test1.txt");

# some file activity

close(FILE);

closedir (DIRHANDLE)

Category: Directory, Files
Return Value: SCALAR, true if the directory was closed correctly, false if not.
Definition: Closes the directory opened by opendir().


opendir(DIR, ".");

# some directory activity

closedir(DIR);

connect (SOCKET, NAME)

Category: Socket
Return Value: SCALAR, true if the connection was successful, otherwise false.
Definition: Attempts to connect to a remote socket. NAME must be a packed address of the correct type for the socket.

cos ([EXPR])

Category: Math
Return Value: SCALAR, the cosine of EXPR or else $_ is used if no expression is specified.
Definition: Calculates a cosine.


$temp = cos(60);

crypt (TEXT, SALT)

Category: String
Return Value: SCALAR, an encrypted string.
Definition: Encrypts TEXT using a key (either SALT or the first two letters of TEXT).


$encyptedString = crypt("Password","TR");

dbmclose (HASH)

Category: Database
Return Value: SCALAR, true if the close was successful, false otherwise.
Definition: Undoes the linking of HASH to a dbm file.

Tip
This function has been superseded by the untie() function.

dbmopen (HASH, DATABASE_NAME, MODE)

Category: Database
Return Value: None
Definition: Links HASH to DATABASE_NAME. If the database does not exist, a new one with the specified MODE will be created.

Tip
This function has been superseded by the tie() function.

defined (EXPR)

Category: Miscellaneous
Return Value: SCALAR, true if EXPR has a real value, false otherwise.
Definition: There is a subtle distinction between an undefined null value 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()).


@iexist = (1,2,3);

print("exists.\n") if defined(@iexist);

print("does not exist.\n") unless defined(@iexist);

delete (EXPR)

Category: Hash
Return Value: SCALAR, the deleted value or the undefined value if nothing was deleted.
Definition: Deletes an entry from an associative array. EXPR is the key for the entry to delete.


%Hash = ('Jan' => 'One', 'Feb' => 'Two', 'Mar' => 'Three');

delete($Hash{'Jan'});

die ([LIST])

Category: Process
Return Value: None.
Definition: Terminates execution of the Perl script, printing LIST to STDERR. The exit value is the current value of $! which may have been set by a previous function. If $! has a value of zero, $? will be returned instead. If $? is zero, it exits with an exit value of 255. If LIST does not end in a newline, the text similar to "at test.pl at line 10" will be appended to the end.


die("Something fatal has happened and the script must die!");

do (SCRIPTNAME)

Category: Miscellaneous
Return Value: None
Definition: Executes the contents of a file as a Perl script. It is usually used to include subroutines however it has been mostly superseded by use() and require().

dump ([LABEL])

Category: Process, UNIX
Return Value: None.
Definition: Causes the program to create a binary image or core dump. You can reload the image using undump program. When reloaded, the program begins execution from the optional 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 (HASH)

Category: Hash
Return Value: ARRAY, an entry (the key-value pair) in HASH.
Definition: Allows iteration over the entries in an associative array. Each time it is evaluated, another key-value pair is returned. When all the entries have been returned, it returns an empty array.


%NumberWord = ('1' => 'One', '2' => 'Two', '3' => 'Three');

while (($key, $value) = each(%NumberWord)) {

    print("$key: $value\n");

}

endgrent ( )

Category: Group, UNIX
Return Value: SCALAR, true if successful, false if not.
Definition: Closes the /etc/group file used by getgrent() and other group related functions.


($name, $pw, $gid, @members) = getgrent();

endgrent();

endhostent ( )

Category: Host, Sockets, UNIX
Return Value: SCALAR, true if successful, false if not.
Definition: Closes the TCP socket used by gethostbyname() and host related functions.


$host = gethostbyname("lynch");

endhostent();

endnetent ( )

Category: Network, UNIX
Return Value: SCALAR, true if successful, false if not.
Definition: Closes the /etc/networks file used by getnetent() and network related functions.


($name, $aliases, $addrtype, $net) = getnetent();

endnetent();

endprotoent ( )

Category: Protocol, UNIX
Return Value: SCALAR, true if successful, false if not.
Definition: Closes the /etc/protocols file used by getprotoent() and protocol related functions.


($name, $alias, $protocol) = getprotoent();

endprotoent();

endpwent ( )

Category: Password, UNIX
Return Value: SCALAR, true if successful, false if not.
Definition: Closes the /etc/passwd file used by getpwent() and password related functions.


($name, $pass, $uid, $gid, $quota, $name, 

    $gcos, $logindir, $shell) = getpwent();

endpwent();

endservent ( )

Category: Server, UNIX
Return Value: SCALAR, true if successful, false if not.
Definition: Closes the /etc/servers file used by getservent() and related functions.


($name, $aliases, $port, $protocol) = getservent();

endservent();

eof ([FILEHANDLE])

Category: File
Return Value: SCALAR, true if the next read on FILEHANDLE will be at the end of file, false if not.
Definition: Tests for the end of a 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 a pseudo file is created of the files listed on the command line. This lets you test for the end of the last file on the command line.


open(FILE, "test1.txt");

# some file activity

print("eof() returned ", eof(FILE) ? "TRUE" : "FALSE", "\n");

close(FILE);

eval ([EXPR | BLOCK])

Category: Miscellaneous
Return Value: The undefined value if a syntax error, a runtime error, or a die() function occurs. Otherwise, the return value is the value of EXPR or the last statement in BLOCK. The return value can be any type.
Definition: Treats the expression like a Perl program and executes it. As the context of this execution is the same as that of the script itself, variable definitions and subroutine definitions persist. Syntax errors, runtime errors, and execution of the die() function are trapped and an undefined result is returned. If such an error does occur $@ 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).

Tip
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. See Chapter 13, "Handling Errors and Signals," for more information.


$answer = 3;

eval("$answer = ;");

if ($@ eq "") {

    print("eval() returned success.\n");

}

else {

    print("eval() error: $@");

}

exec (LIST)

Category: Process
Return Value: None.
Definition: This function passes control from the script to an external system command. There is no return from this call. Note that system() calls external commands and does return.


exec("cat /etc/motd");

exists (EXPR)

Category: Hash
Return Value: SCALAR, true if EXPR is an entry in a hash, false if not.
Definition: Tests whether a given key value exists in an associative array.


%test = ( 'One' => '1', 'Two' => '2');

if (exists($test{'One'})) {

    print("exists() returned success.\n");

}

else {

    print("exists() returned an error.\n");

}

exit ([EXPR])

Category: Process
Return Value: None.
Definition: Evaluates EXPR and exits the program with that value as the exit code. The default value for the exit code is 0 if no argument is supplied. If an END block
has been defined, it will be called. Also, object destructors may be called before the process truly ends.


exit(16);

exp ([EXPR])

Category: Math
Return Value: SCALAR, the natural log base (e) to the power of EXPR.
Definition: Returns the natural log base (e) to the power of EXPR. If no parameter is specified, $_ is used.


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

fcntl (FILEHANDLE, FUncTION, PACKED_FLAGS)

Category: File, UNIX
Return Value: None.
Definition: 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. See the perlfunc man page for more information.

fileno (FILEHANDLE)

Category: File
Return Value: SCALAR, the file descriptor for FILEHANDLE.
Definition: Returns the file descriptor given a file handle. File descriptors are useful when using bitmaps for the select() function.


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

flock (FILEHANDLE, OPERATION_FLAGS)

Category: File
Return Value: SCALAR, true if successful, false if not.
Definition: Lets you access file locks. You can place an exclusive lock, place a shared lock, or remove locks. You can find more information about flock() in section 2 of the UNIX manual pages.

fork ( )

Category: Process UNIX
Return Value: SCALAR, the pid of the child process or undef is unsuccessful.
Definition: Starts a child process. Both child and parent processes start executing the line of code immediately following the fork() call. You can find more information about fork() in section 2 of the UNIX manual pages.

formline (PICTURE, LIST)

Category: Miscellaneous
Return Value: None.
Definition: This internal function is used by the format mechanism. It allows direct manipulation of the format process by adding values to the format accumulator ($^A). For more information about formats, see Chapter 11, "Creating Reports."

getc ([FILEHANDLE])

Category: File, Input
Return Value: SCALAR, the inputted character. Null if at end of file.
Definition: Returns the next character FILEHANDLE or STDIN if no filehandle is specified.


open(FILE, "/etc/motd");

print "getc() ", getc(FILE), "\n";

close(FILE);

getgrent ( )

Category: Group, UNIX
Return Value: in Scalar Context : Returns the next group name or the undefined value if no more groups or an error occurred.
Return Value in Array Context : ($name, $passwd, $gid, $members) or an empty list.
Definition: Returns information about groups taken from the /etc/group system file. If called repeatedly, it will iterate through the entries in the /etc/group file.


($name, $pw, $gid, @members) = getgrent();

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

getgrgid (GID)

Category: Group, UNIX
Return Value: in Scalar Context: The next group name that belongs to GID.

Return Value in Array Context: ($name, $passwd, $gid, $members) or an empty list.
Definition: Returns information about groups taken from the /etc/group system file.


($grname, $grpw, $gid, @members) = getgrgid(0);

print("getgrgid() Returns group name given GID [$grname]\n");

getgrname (NAME)

Category: Group, UNIX
Return Value: in Scalar Context: The next group id that belongs to NAME.
Return Value in Array Context: ($name, $passwd, $gid, $members) or an empty list.
Definition: Returns information about groups taken from the /etc/group system file.


($grname, $grpw, $gid, @members) = getgrnam("root");

print("getgrnam() Returns group GID given name [$gid]\n");

gethostbyaddr (ADDRESS, AF_INIT)

Category: Host, Socket
Return Value: in Scalar Context: Name of host addressed by ADDRESS or undefined if the host could not be found.
Return Value in Array Context: ($name, $aliases, $addrtype, $length, @addrs) or an empty list.
Definition: Looks in the /etc/hosts system file or checks a Domain Name Server for a server with ADDRESS. The value for AF_INIT is always 2.


use Socket;

$addr = pack('C4', (140,203,7,103));

($name, $alias, $addrtype, $length, @addrs) = gethostbyaddr($addr, AF_INET);

print("gethostbyaddr() [$alias].\n");

gethostbyname (NAME, [PROTOCOL])

Category: Host, Socket
Return Value: in Scalar Context: Address of the host called NAME or undefined if the host could not be found.
Return Value in Array Context: ($name, $aliases, $addrtype, $length, @addrs) or an empty list.
Definition: Looks in the /etc/hosts system file or checks a Domain Name Server for a server called NAME.


($name, $alias, $addrtype, $length, @addrs) = gethostbyname("lynch");

print("gethostbyname() [$alias].\n");

gethostent ( )

Category: Host, UNIX
Return Value: in Scalar Context: Name of the next host in /etc/hosts. or the undefined value.
Return Value in Array Context: ($name, $aliases, $addrtype, $length, @addrs) or an empty list.
Definition: Looks in the /etc/hosts system file.


($name, $alias, $addrtype, $length, @addrs) = gethostent();

print("gethostent() [$alias].\n");

getlogin ( )

Category: Process, UNIX
Return Value: SCALAR, the name of the current login.
Definition: Gets the current login name from the /etc/utmp system file. Use getpwuid()for more information on the login because the information stored in /etc/utmp is limited.


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

getnetbyaddr (ADDRESS, ADDR_TYPE)

Category: Network
Return Value: in Scalar Context: The network name that has an address of ADDRESS or undefined.
Return Value in Array Context: ($name, $aliases, $addrtype, $net) or an empty list.
Definition: Looks for the network information in the /etc/networks system file.


($addrtype) = (getnetent())[2];

($name, $alias, $addrtype, $net) = getnetbyaddr($net, $addrtype);

print("getnetbyaddr() Reads /etc/networks [$name]\n");

getnetbyname (NAME)

Category: Network
Return Value: in Scalar Context: The network address of NAME or undefined.
Return Value in Array Context: ($name, $aliases, $addrtype, $net) or an empty list.
Definition: Looks for the network information in the /etc/networks system file.


($name, $alias, $addrtype, $net) = getnetbyname("localnet");

print("getnetbyname() Reads /etc/networks [$name]\n");

getnetent ( )

Category: Network
Return Value in Scalar Context: The next network name in /etc/networks or undefined.
Return Value in Array Context: ($name, $aliases, $addrtype, $net) or an empty list.
Definition: When called repeatedly, it iterates over the information in the /etc/networks system file.


($name, $alias, $addrtype, $net) = getnetent();

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

getpeername (SOCKET)

Category: Sockets
Return Value: SCALAR, the address of the remote side of a socket connection represented by SOCKET.
Definition: Gets the packed address of the remote side of a socket. The address can then be used with the unpack() function to retrieve the protocol family, port and ip address values.


$sockaddr = 'S n a4 x8';

$packedRemoteAddr = getpeername(S);

($family, $port, $remoteAddr) = unpack($sockaddr,$packedRemoteAddr);

getpgrp (PID)

Category: Groups, Process, UNIX
Return Value: SCALAR, the current process group for PID. If PID is not specified or 0 is used, the current group of the current process is returned.
Definition: Finds the current process group for a given pid.


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

getppid ( )

Category: Process, UNIX
Return Value: SCALAR, the pid of the parent process.
Definition: Finds the pid of the parent process.


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

getpriority (WHICH, WHO)

Category: Process, UNIX
Return Value: SCALAR, the current priority associated with the parameters.
Definition: Returns the current priority of WHO (the pid, group pid, uid, or 0 for the current process). The WHICH parameter can one of PRIO_PROCESS (0), PRIO_PGGRP (1), PRIO_USER (2).


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

getprotobyname (NAME)

Category: Protocols, UNIX
Return Value: in Scalar Context: The protocol number assigned to NAME.
Return Value in Array Context: ($name, $aliases, $proto) or an empty list. $proto is the protocol number.
Definition: Looks in the /etc/protocols system file for the protocol called NAME.


($name, $alias, $proto) = getprotobyname("IP");

print("getprotobyname() /etc/proto [$name, $alias, $proto].\n");

getprotobynumber (NUMBER)

Category: Protocols, UNIX
Return Value: in Scalar Context: The protocol name associated with NUMBER.
Return Value in Array Context: ($name, $aliases, $proto) or an empty list.
Definition: Looks in the /etc/protocols system file for NUMBER.


($name, $alias, $proto) = getprotobynumber(0);

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

getprotoent ( )

Category: Protocols, UNIX
Return Value: ARRAY. ($name, $aliases, $proto) or an empty list.
Definition: When called repeatedly, getprotoent() iterates over the /etc/protocols system file.


($name, $alias, $proto) = getprotoent();

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

getpwent ( )

Category: Password, UNIX
Return Value: in Scalar Context: The username.
Return Value in Array Context: ARRAY. ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) or an empty list.
Definition: When called repeatedly, getpwent() iterates over the /etc/passwd system file.


($name, $pass, $uid, $gid, $quota, $name, $gcos, $dir, $shell) = getpwent();

print("getpwent() /etc/passwd [$dir, $shell].\n");

getpwnam (NAME)

Category: Password, UNIX
Return Value: in Scalar Context: The userid of NAME.
Return Value in Array Context: ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) or an empty list.
Definition: Looks in the /etc/passwd system file for NAME.


($name, $pass, $uid, $gid, $quota, $name, 

    $gcos, $dir, $shell) = getpwnam("root");

print("getpwnam() /etc/passwd [$dir, $shell].\n");

getpwuid (UID)

Category: Password, UNIX
Return Value: in Scalar Context: The username of UID.
Return Value in Array Context: ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) or an empty list.
Definition: Looks in the /etc/passwd system file for UID.


($name, $pass, $uid, $gid, $quota, $name, 

    $gcos, $dir, $shell) = getpwuid(0);

print("getpwuid() /etc/passwd [$dir, $shell].\n");

getservbyname (NAME, PROTOCOL)

Category: Protocol, Service, Socket, UNIX
Return Value: in Scalar Context: The port number.
Return Value in Array Context: ($name, $aliases, $port, $proto) or an empty list.
Definition: Gets services by name. Looks in the /etc/services system file.


($name, $aliases, $port, $protol) = getservbyname("tcpmux", "tcp");

getservbyport (PORT_NUMBER, PROTOCOL)

Category: Protocol, Service, Socket, UNIX
Return Value: in Scalar Context: The service name.
Return Value in Array Context: ($name, $aliases, $port, $proto) or an empty list.
Definition: Gets services by port. Looks in the /etc/services system file.


($name, $aliases, $port, $protol) = getservbyport(512, "tcp");

getservent ( )

Category: Protocol, Service, Socket, UNIX
Return Value: in Scalar Context: The next service name.
Return Value in Array Context: ($name, $aliases, $port, $proto) or an empty list.
Definition: When called repeatedly, iterates over the /etc/services system file.


($name, $aliases, $port, $protol) = getservent();

print("getservent() /etc/servers [$name].\n");

getsockname (SOCKET)

Category: Sockets
Return Value: SCALAR, the packed address of the local end of the socket.
Definition: Finds out the address of your script's socket.


$packedAddr = getsockname(S);

($family, $port, $localAddr) = unpack('S n a4 x8', $packedAddr);

getsockopt (SOCKET, LEVEL, OPTNAME)

Category: Sockets
Return Value: SCALAR, the socket option requested or the undefined value.
Definition: Gets the value of a specified socket option.

glob (EXPR)

Category: File
Return Value: ARRAY, the list of files represented by EXPR.
Definition: Looks for file name that match EXPR. You can use wildcards in EXPR.


@files = glob("*.txt");

gmtime ([EXPR])

Category: Time
Return Value: in Scalar Context: A string like 'Sat Jul 13 07:34:46 1986' describing EXPR.
Return Value in Array Context: ($sec, $min, $hour, $mday, $mon, $year, $wday, $ydat, $isdst).
Definition: Breaks EXPR (a number of seconds since 1st Jan 1970) into a 9-element list. If no argument is used the current time is used. If your system supports POSIX time zones, the time returned is localized for the Greenwich Mean Time time zone. Note that $mon ranges from 0..11, $wday ranges from 0..6, and $year does not handle centuries.


($sec, $min, $hour, $mday, $mon, $year, $wday, $ydat, $isdst) = gmtime();

print "gmtime() 19$year-$mon-$mday\n";

grep (BLOCK | EXPR, LIST)

Category: Regular Expressions
Return Value: in Scalar Context: The number of times that BLOCK or EXPR evaluated to true.
Return Value in Array Context: A list of the elements of LIST that causes BLOCK or EXPR to evaluate as true.
Definition: Evaluates the expression or block for each of the elements in LIST. Think of this function as having an internal foreach loop. Each element in LIST is assigned to $_ and then the block or expression is evaluated. The most common use for this is with a pattern match operation as the expression, and a list of strings to be processed. You may be tempted to use grep() as an easy way to interate over an array as shown in the second example below, don't do this. Use the map() function instead.


# Look for all elements that begin with the letter T.

@a = ('One', 'Two', 'Three', 'Four', 'Five');

print("grep(), ", grep(/^T/, @a), "\n");



# Print all elements in a list.

@a = ('One', 'Two', 'Three', 'Four', 'Five');

grep( print("$_\n"), @a);

hex (EXPR)

Category: Math, String
Return Value: SCALAR, the decimal value of EXPR.
Definition: Converts EXPR from hexadecimal to decimal. For example, hex('FF0') will return '4080'. You can use the string returned as a number because Perl will automatically convert strings to numbers in numeric contexts.


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

import ( )

Category: Miscellaneous
Return Value: None.
Definition: This is the only user-defined function in this list. If a module has an import() function then the use() function will call it as the module is being loaded. You can use the import() function to initialize variables, open files, or do any other setup work.

index (STRING, SUBSTRING, [POSITION])

Category: String
Return Value: SCALAR, the position of the first occurrence of SUBSTRING in STRING at or after POSITION or -1 if not found.
Definition: When called repeatedly, you can iterate over all the occurrences of SUBSTRING in STRING. The returned value is an offset from $[ (which is normally zero). If $[ 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.


$answer1 = index("abcdefghijiklmdef:-)", "def");

$answer2 = index("abcdefghijiklmdef", "def", $answer1 + 3);

print("index() def is at $answer1 and next at $answer2\n");

int ([EXPR])

Category: Math
Return Value: SCALAR, the integer portion of EXPR.
Definition: Chops of any fractional part of EXPR or $_ if no expression is specified.
For example, int(21.45) would return 21.


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

ioctl (FILEHANDLE, FUncTION, SCALAR)

Category: File, UNIX
Return Value: SCALAR, true if successful; false if not and the undefined value in some cases.
Definition: Controls Input/Output operations, mainly used for terminals. It calls the UNIX ioctl() function with the specified parameters. 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. You can find more information about ioctl() in section 2 of the UNIX manual pages.

join (EXPR, LIST)

Category: Array, String
Return Value: SCALAR, a string with each element of LIST alternating with EXPR.
Definition: Concatenates all of the elements of LIST together with EXPR as the glue. For example, join('!', ('QQ', 'AA')) will return 'QQ!AA'.


@listone = (0, 1, 2, 3);

print("join() ", join("-",@listone), "\n");

keys (HASH)

Category: Array, Hash
Return Value: in Scalar Context: The number of keys and, therefore, the number of entries in HASH.
Return Value in Array Context: All of the keys to HASH in no particular order.
Definition: Gets a list of all keys in HASH. The returned list is ordered by the internal storage requirements, so it is often useful to use the sort() function before processing. For example, sort(keys(%hash)).


%hash = ('One' => 1, 'Two' => 2, 'Three' => 3, 'Four' => 4);

print("keys() ", join("-", keys(%hash)), "\n");

kill (SIGNAL, LIST)

Category: Process
Return Value: SCALAR, the number of processes successfully signaled.
Definition: Sends SIGNAL to the processes identified by LIST. If SIGNAL is negative then process groups are killed instead.

lc (EXPR)

Category: String
Return Value: SCALAR, a copy of EXPR with all letters in lowercase.
Definition: Creates a copy of EXPR with all letters in lowercase.


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

lcfirst (EXPR)

Category: String
Return Value: SCALAR, a copy of EXPR with the first letter in lowercase.
Definition: Creates a copy of EXPR with the first letter in lowercase.


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

length ([EXPR])

Category: String
Return Value: SCALAR, the number of characters in EXPR.
Definition: Determines the numbers of characters in EXPR. If no expression is supplied $_ is used.


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

link (OLD_FILE, NEW_FILE)

Category: File, UNIX
Return Value: SCALAR, true if successful or false if not.
Definition: Creates a hard link called NEW_FILE linking to the filename called OLD_FILE.


print("The result from link() is ", link("/usr/local", "/tmp/link"), "\n");

listen (SOCKET, QUEUESIZE)

Category: Socket
Return Value: SCALAR, true if successful or false if not.
Definition: Listens for connections on a socket. QUEUESIZE specifies how many processes can wait for connections.

local (LIST)

Category: Scope
Return Value: None.
Definition: Makes all the variables in LIST to be local to the current block. The my() function is better than local() because it also creates new copies of the variables for each recursive call of a subroutine. Don't use local() inside loops. Variables marked using local() can be seen by functions called from inside the current block.


local($numTires) = 10;

localtime ([EXPR])

Category: Time
Return Value: in Scalar Context: A string like 'Sat Jul 13 07:34:46 1986' describing EXPR.
Return Value in Array Context: ($sec, $min, $hour, $mday, $mon, $year, $wday, $ydat, $isdst).
Definition: Breaks EXPR (a number of seconds since 1st Jan 1970) into a 9-element list. If no argument is used the current time is used. If your system supports POSIX time zones, the time returned is localized for the current time zone. Note that $mon ranges from 0..11, $wday ranges from 0..6, and $year does not handle centuries. If no expression is specified, the current time is used.


($sec, $min, $hour, $mday, $mon, $year, $wday, $ydat, $isdst) = localtime();

print("localtime() 19$year-$mon-$mday\n");

log ([EXPR])

Category: Math
Return Value: SCALAR, the logarithm (using the natural logarithm base e) of EXPR or $_ if no expression is specified.
Definition: Determines the logarithm (using the natural logarithm base e) of the expression.


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

lstat (FILEHANDLE | EXPR)

Category: File, UNIX
Return Value: ARRAY, ($device, $inode, $mode, $nlink, $uid, $gid, $rdev, $size, $atime, $mtime, $ctime, $blksize, $blocks) or an empty list if an error occurs.
Definition: Gets the file statistics of a symbolic link rather that the file pointed to the link. If the parameters do not refer to a symbolic link, the file statistics are still returned. Note that, like the filetest operators, lstat() can take the special underscore filehandle (_) which means that the test is carried out on the same filehandle as the last filetest, stat() or lstat() call.


($device, $inode, $mode, $nlink, $uid, $gid, $rdev, $size, 

    $atime, $mtime, $ctime, $blksize, $blocks) = lstat("/tmp/link");

print("lstat() $device, $inode, $ctime \n");

map (BLOCK | EXPR, LIST)

Category: Array
Return Value: ARRAY, a list of the results of evaluating BLOCKor EXPR which each element of LIST being assigned to $_.
Definition: Evaluates the specified expression (or block) for each element of LIST. This is done by assigning each element to $_ and evaluting the expression (or block) in an array context. Therefore, the returned array may have more elements than LIST.


# Increment each element by one.

@array = (0..3);

@result = map($_ + 1, @array);

print("Before map: @array\n");

print("After  map: @result\n");



# Print all elements in a list.

@array = ('One', 'Two', 'Three', 'Four', 'Five');

map( print("$_\n"), @array);

mkdir (FILENAME, [MODE])

Category: Directory
Return Value: SCALAR, true if successful or false if not.
Definition: Creates a directory call DIRNAME, with the mode specified by MODE. The mode is specified using an octal number and is ignored under Windows 95 or Windows NT. If the directory can't be created, $! is set to the operating system error.


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

msgctl (ID, COMMAND, ARG)

Category: Inter-process Communications, Message Queues
Return Value: SCALAR, true if successful; false if not and the undefined value in some cases.
Definition: Controls message queue operations. It calls the UNIX msgctl() function with the specified parameters. 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. You can find more information about msggctl() in section 2 of the UNIX manual pages.

msgget (KEY, FLAGS)

Category: Inter-process Communication, Message Queue
Return Value: SCALAR, the message queue id or the undefined value if an error occurred.
Definition: Determines the message queue id.

msgrcv (QUEUE_ID, BUFFER, BUFFER_SIZE, TYPE, FLAGS)

Category: Inter-process Communication, Message Queue
Return Value: SCALAR, true if successful or false if not.
Definition: Gets a message from QUEUE_ID. The message is placed into BUFFER.

msgsnd (QUEUE_ID, BUFFER, FLAGS)

Category: Inter-process Communication, Message Queue
Return Value: SCALAR, true if successful or false if not.
Definition: Send a message to QUEUE_ID. The message to be sent should be in BUFFER.

my (LIST)

Category: Scope
Return Value: None.
Definition: Declares each of the variables listed to be local to the lexical unit (block or file). See Chapter 5 "Functions," for more information.


# Define the function foo with four local variables.

sub foo {

    my($numTires) = shift;

    my(@params) = @_;

    my($tireType, $tirePressure);

}

oct ([EXPR])

Category: Math, String
Return Value: SCALAR, the decimal value of EXPR.
Definition: Converts EXPR from octal to decimal. For example, oct('0760') will return '496'. You can use the string returned as a number because Perl will automatically convert strings to numbers in numeric contexts.


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

open (FILEHANDLE | EXPR | FILENAME)

Category: File
Return Value: SCALAR, true if the file is opened, false otherwise.
Definition: 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 special file name '-' refers to STDIN and '>-' refers to STDOUT.

The file name string may be prefixed with the following values to indicate the mode:

Prefix ValueDescription
<
read access, this is the default
>
write access
+>
create a file with read/write accesss
+<
read/write access to an existing file
>>
append to a file
" CMD |"
Execute CMD as an operating system command and pipe the resulting output back to your Perl script as FILEHANDLE
"| CMD"
Pipe output to FILEHANDLE into CMD


$FILE = "foo.dat"

open(FILE) or die("Unable to open $FILE because: $!");

opendir (DIRHANDLE, EXPR | DIRNAME)

Category: Directory
Return Value: SCALAR, true if the directory is opened, false otherwise.
Definition: Opens a connection between the directory handle and the directory name. If you use an expression for the second parameter, it is expected to evaluate to a directory name.


$dir = "/tmp"

opendir(DIR, $dir) or die("Unable to open $dir because $!");

ord ([EXPR])

Category: String
Return Value: SCALAR, the numeric value of the first character of EXPR or $_ if no expression is specified.
Definition: Returns the numeric ascii code of the first character in the expression. For example, ord('A') returns a value of 65. print("ord() ", ord('G'), "\n");

pack (TEMPLATE, LIST)

Category: String
Return Value: SCALAR, a packed version of the data in LIST using TEMPLATE to determine how it is coded.
Definition: Converts LIST into a data structure-possibly packed with binary information. You can find additional information by looking at the perfunc man page, the perlfunc.htm file in your docs directory, or by pointing your web browser to ftp://ftp.metronet.com/pub/perl/doc/manual/html/perlfunc/pack.html. You can use any of the following specifiers in the template string.

Format Specifier
Description
@
Null fill to absolute position.
A
Ascii string with spaces to pad.
a
Ascii string with nulls to pad.
b
Bit string (ascending bit order).
B
Bit string (descending bit order).
c
Signed char value.
C
Unsigned char value.
d
Double-precision float in the native format.
f
Single-precision float in the native format.
h
Hex string (low nybble first).
H
Hex string (high nybble first).
i
Signed integer value.
I
Unsigned integer value.
l
Signed long integer value.
L
Unsigned long integer value.
n
Short integer "network" order.
N
Long integer "network" order.
p
Pointer to a null-terminated string.
P
Pointer to a structure (fixed-length string).
s
Signed short integer value.
S
Unsigned short integer value.
u
UUencoded string.
v
Short integer "VAX" (little-endian) order.
V
Long integer "VAX" (little-endian) order.
x
Null byte.
X
Back up a byte.

A concise form of template can be used by appending a number after any letter to repeat that format specifier. For example, a5 indicates that five letters are expected. b32 indicates that 32 bits are expected. H8 indicates that 8 nybbles ( or 4 bytes) are expected. P10 indicates that the structure is 10 bytes long. 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 particular network and floating point formats). It should be possible to unpack the data using the same format specification with an unpack() call.


Use Socket;

@address = (140, 203, 7, 103)

$addr = pack('C4', @address);

print("@address is packed as: $addr\n");

pipe (READHANDLE, WRITEHANDLE)

Category: Inter-process Communication
Return Value: SCALAR, true if successful, false if not.
Definition: Opens a pair of connected pipes.

pop (ARRAY_VARIABLE)

Category: Array
Return Value: SCALAR, the last element in the specified array.
Definition: Removes the last element from the specified array. Note that the array will be shortened by one.


@a = (1, 2, 3, 4);

print("pop() ", pop(@a), "leaves ",@a, "\n");

pos ([SCALAR])

Category: Regular Expression
Return Value: SCALAR, the position of the last matched substring of the last m//g operation.
Definition: Used to find the offset or position of the last matched substring. If SCALAR is specified, it will return the offset of the last match on that scalar variable. You can also assign a value to this function (for example, pos($foo) = 20;) in order to change the starting point of the next match operation.


$name = "alpha1 alpha2 alpha3 alpha4";

$name =~ m/alpha/g;

print("pos() ", pos($name), "\n");

print [FILEHANDLE] ([LIST])

Category: Output
Return Value: SCALAR, true if successful or false otherwise.
Definition: Prints LIST to the file represented by FILEHANDLE. If no file handle is specified STDOUT will be used. This default file handle may be altered using the select() operator. If no list argument is specified $_ is printed.


# This example may look funny, but it works. Go ahead and

# try it!

#

    print(" returns ", print("print()"), " on success.\n");

#

# The inside print() function is evaluated first, then the

# outer print() function is evaluated.

printf [FILEHANDLE] (FORMAT, LIST)

Category: Output
Return Value: SCALAR, true if successful or false otherwise.
Definition: Uses format specifiers to print LIST in specific ways. If no file handle is specified, STDOUT is used. For more information, see "Example: Printing Revisited," in Chapter 9 "Using Files."


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

push (ARRAY, LIST)

Category: Array
Return Value: SCALAR, the number of elements in the new array.
Definition: Appends the elements in LIST to the end of the specified array.


# Find out how any elements are in @array. This works because

# you are essentially appending an empty array.

@array = ('A'..'R');

print("There are ", push(@array), "elements.\n");



@array = ( 1, 2 );

print("There are ", push(@array, (3, 4, 5)), "elements.\n");

q (LIST)

Category: String
Return Value: SCALAR, a single-quoted string.
Definition: q() can be used instead of single quotes. This is not really a function, more like an operator, but you'll probably look here if you see it in another programmer's program without remembering what it is. You can actually use any set of delimiters, not just the parentheses.


print(q(This is a single quoted string without interpolation), "\n");

qq (LIST)

Category: String
Return Value: SCALAR, a double-quoted string.
Definition: qq() can be used instead of double quotes. This is not really a function, more like an operator, but you'll probably look here if you see it in another programmer's program without remembering what it is. You can actually use any set of delimiters, not just the parentheses.


print(qq(This is a double quoted string with interpolation\n));

quotemeta (EXPR)

Category: Regular Expression, String
Return Value: SCALAR, a string with all meta-characters escaped.
Definition: Escapes all meta-characters in EXPR. For example, quotemeta("AB*..C") returns "'AB\*\.\.C".


print quotemeta("AB*\n[.]*");

qw (LIST)

Category: Array, String
Return Value: ARRAY, a list consisting of the element of LIST evaluated as if they were single-quoted.
Definition: qw() is a quick way to specify a lot of little single-quoted words. For example, qw(foo, bar, baz) is equivalent to 'foo', 'bar', 'baz'. Some programmers feel that using qw makes Perl scripts easier to read. This is not really a function, more like an operator, but you'll probably look here if you see it in another programmer's program without remembering what it is. You can actually use any set of delimiters, not just the parentheses.


@array = qw(This is a list of words without interpolation);

qx (LIST)

Category: String
Return Value: SCALAR, the return value from the executed system command.
Definition: qx() is an alternative to using back-quotes to execute system commands. For example, qx(ls -l) will execute the UNIX ls command using the -l command-line option. This is not really a function, more like an operator, but you'll probably look here if you see it in another programmer's program without remembering what it is. You can actually use any set of delimiters, not just the parentheses.


# summarize disk usage for the /tmp directory

# and store the output of the command into the

# @output array.

#

@output = qx(du -s /tmp);

rand ([EXPR])

Category: Math
Return Value: SCALAR, a random number between 0 and EXPR or between 0 and 1 if no expression is specified.
Definition: Generates random numbers. The value of EXPR should be positive (use the abs() function if needed). As the function calls a pseudo random generator, it generates the same sequence of numbers unless the initial seed value is altered with srand().


# print a random number between 0 and 10.

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

read (FILEHANDLE, BUFFER, LENGTH, [OFFSET])

Category: File, Input
Return Value: SCALAR, the number of bytes read or the undefined value.
Definition: Reads, or attempts to read, LENGTH number of bytes from the file associated with FILEHANDLE into BUFFER. If an offset is specified, Perl will start reading the file from that point. For example, an offset of 100 will cause Perl to bypass the first 100 bytes of the file.


sub readFile {

   my($buffer) = "";



   open(FILE, "/etc/services") or die("Error reading file, stopped");

   read(FILE, $buffer, 10);

   print("read() $buffer\n");

   close(CLOSE)

}

readdir (DIRHANDLE)

Category: Directory, Files
Return: Value in Scalar Context: The name of the next file in the directory connected to DIRHANDLE.
Return Value in Array Context: A list containing all of the files in the directory connected to DIRHANDLE.
Definition: Reads directory entries.


opendir(DIR, "/tmp");

@file = readdir(DIR);

print("readdir() @files\n");

readlink ([EXPR])

Category: File, UNIX
Return Value: SCALAR, the value of the symbolic link represented by EXPR or $_ if no expression is specified. The undefined value is returned if an error arises.
Definition: Gets the value of a symbolic link. System errors are returned $!.

recv (SOCKET, BUFFER, LENGTH, FLAGS)

Category: Sockets
Return Value: SCALAR, the address of the sender or the undefined value.
Definition: Places information from a socket into a buffer.

ref (EXPR)

Category: Miscellaneous
Return Value: SCALAR, the data type of EXPR.
Definition: Gets the data type of a variable. For example, 'ARRAY', 'CODE', 'GLOB', 'HASH', 'REF', or 'SCALAR' might be returned. If a variable was blessed with the bless() function, then the new data type will be returned. The new data type will normally be a class name.


$foobar = { };

bless($foobar, 'ATMPCLASS');

print("ref() \$foobar is now in class ", ref($foobar), "\n";

rename (OLDNAME, NEWNAME)

Category: File
Return Value: SCALAR, true if successful, false if not.
Definition: Changes the name of a file. You can use this function to change the directory location of a file as long as you don't cross file-system boundaries.


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

reset ([EXPR])

Category: Regular Expression
Return Value: SCALAR, always returns true.
Definition: This a way of resetting variables in the current package (especially pattern match variables). The expression is interpreted as a list of single characters. All variables starting with those characters are reset. Hyphens may be used to specify ranges of variables to reset. If called without any argument it simply resets all search matches. Variables that have been declared using the my() function will not be reset.


reset('R');

reset('d-f');

reset();

Caution
Using reset() can reset system variables you may not want to alter-like the ARGV and ENV variables.

reverse (LIST)

Category: Array, String
Return Value in Scalar Context: A string with characters of the first element of LIST reversed.
Return Value in Array Context: The elements of LIST in reverse order.
Definition: Reverses the order of a string or list. No sorting is done, the list or string is simply reversed.


@array = (1, 2, 3);

print("reverse() ", reverse(@array), "\n");

rewinddir (DIRHANDLE)

Category: Directory
Return Value: None.
Definition: Lets you start reading directory entries all over again.


# Open the current directory

opendir(DIR, ".");

# Print all of the directory entries.

print("1st Time: ");

map( print("$_ ") , readdir(DIR));

print("\n");



# Print message verifying that there are

# no more directory entries to read.

print("The last file has already been read!\n\n") unless readdir(DIR);



# Go back to the beginning.

rewinddir(DIR);



# Print all of the directory entries again.

print("2nd Time: ");

map( print("$_ ") , readdir(DIR));

print("\n");



closedir(DIR);

rindex (STRING, SUBSTRING, [POSITION])

Category: String
Return Value: SCALAR, the position of the last occurrence of SUBSTRING in STRING at or before POSITION or -1 if not found.
Definition: When called repeatedly, you can iterate over all the occurrences of SUBSTRING in STRING. The returned value is an offset from $[ (which is normally zero). If $[ 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.


$answer1 = rindex("abcdefghijiklmdef", "def");



# use the first position found as the offset to the next search.

# note that the length of the target string is subtracted from

# the offset to save time.

$answer2 = rindex("abcdefghijiklmdef", "def", $answer1 - 3);



print("rindex() \"def\" is at $answer1 and next at $answer2\n");

rmdir ([DIRNAME])

Category: Directory
Return Value: SCALAR, true if successful or false if not. $! is set if the directory could not be deleted.
Definition: Tries to delete the specified directory. The directory must be empty of all files, symbolic links, and sub-directories.

scalar (EXPR)

Category: Miscellaneous
Return Value: SCALAR, the value of EXPR in a scalar context.
Definition: Forces the argument to be interpreted in a scalar context, rather than as a list. For example, scalar(@array) will return the number of elements in @array.


$numElements = scalar(@array);

seek (FILEHANDLE, POSITION, WHEncE)

Category: File
Return Value: SCALAR, true if successful or false if not.
Definition: Moves to a specified position in a file. You can move relatively to the beginning of the file (WHEncE = 0), the current position (WHEncE = 1), or the end of the file (WHEncE = 2). This function is mainly used with fixed length records to randomly access specific records of the file.

seekdir (DIRHANDLE, POS)

Category: Directory
Return Value: None.
Definition: Allows the position in a directory to be reset to a position saved with telldir(). This is useful when processing directories with readdir().

select ([FILEHANDLE])

Category: File
Return Value: SCALAR, the currently selected filehandle.
Definition: Changes the default file handle used for the print() and write() functions. 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.


open(FILE,">t.out");

    $oldHandle = select(FILE);

        print("This is sent to /tmp/t.out.\n");

    select($oldHandle);

print("This is sent to STDOUT.\n");



# Here is an advanced example which selects an alternate 

# file handle and restores it in one step. The secret is the

# use of parentheses to create a list out of the return values

# of the statements evaluated by the comma operator.



open(FILE, ">t.out");

    select((select(FILE), print("This is sent to t.out.\n"))[0]);

print("This is sent to STDOUT.\n");

select (RBITS, WBITS, EBITS, TIMEOUT)

Category: File, Socket, UNIX

Return Value in Scalar Context: The number of ready descriptors that were found-usually referred to as $nfound.
Return Value in Array Context: ($nfound, $timeleft)-The number of ready descriptors and the amount of time left before a timeout happends.
Definition: Examines file descriptors to see if they are ready or if they have exception conditions pending.

semctl (ID, SEMNUM, CMD, ARG)

Category: Inter-process Communication
Return Value: SCALAR, true if successful; false if not and the undefined value in some cases.
Definition: Controls operations on semaphores.

semget (KEY, NSEMS, FLAGS)

Category: Inter-process Communication
Return Value: SCALAR, a semaphore id or undefined if an error occurs.
Definition: Finds the semaphore associated with KEY.

semop (KEY, OPSTRING)

Category: Inter-process Communication
Return Value: SCALAR, true if successful or false if not.
Definition: Performs semaphore operations like signaling and waiting.

send (SOCKET, BUFFER, FLAGS, [TO])

Category: Socket
Return Value: SCALAR, the number of characters sent or the undefined value if an error occurred.
Definition: Sends the information in a buffer to a socket. If the socket is not connected, you can specify a destination using the TO parameter.

setgrent ( )

Category: Group, UNIX
Return Value: None.
Definition: Rewinds the /etc/group file to the start of the file for subsequent accesses using getgrent().

sethostent (STAYOPEN)

Category: Host, UNIX
Return Value: None.
Definition: Determines if name server queries use UDP datagrams (STAYOPEN = 0) or if the socket connection to the name server should stay open (STAYOPEN = 1). This affects functions like gethostbyname().


sethostent(1);

setnetent (STAYOPEN)

Category: Network, UNIX
Return Value: None.
Definition: Rewinds the /etc/networks file used by getnetent() and other network related functions. If STAYOPEN has a value of 1 then the file is kept open between calls to getnetbyname() and getnetbyaddr().


setnetent(1);

setpgrp (PID, PGRP)

Category: Group, UNIX
Return Value: SCALAR, true if successful or false if not.
Definition: Sets the current process group for the specified process. If PID is zero, the current process group for the current process is set.

setpriority (WHICH, WHO, PRIORITY)

Category: Process, UNIX
Return Value: SCALAR, true if successful or false if not.
Definition: Sets the current priority of WHO (the pid, group pid, uid, or 0 for the current process, group or user). The WHICH parameter can one of PRIO_PROCESS (0), PRIO_PGGRP (1), PRIO_USER (2). The priority is a number representing the level of priority (normally in the range 120 to 20) where the lower the priority the more favorable the scheduling of the process by the operating system.


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

setprotoent (STAYOPEN)

Category: Protocol
Return Value: SCALAR, true if successful or false if not.
Definition: Rewinds the /etc/protocols file used by getprotoent() and other protocol related functions. If STAYOPEN has a value of 1 then the file is kept open between calls to getprotobyname() and getprotobynumber().


setprotoent(1);

setpwent

Category: Password, UNIX
Return Value: SCALAR, true if successful or false if not.
Definition: Rewinds the /etc/passwd file used by getpwent() and other password related functions.


setpwent();

setservent (STAYOPEN)

Category: Services, UNIX
Return Value: SCALAR, true if successful or false if not.
Definition: Rewinds the /etc/services file used by getservent() and other service related functions. If STAYOPEN has a value of 1 then the file is kept open between calls to getservbyname() and getservbyport().


setservent(1);

setsockopt (SOCKET, LEVEL, OPTNAME, OPTVAL)

Category: Socket
Return Value: SCALAR, true if successful or false if not.
Definition: Sets socket options.

shift ([ARRAY])

Category: Array
Return Value: SCALAR, the first element of ARRAY or the undefined value if the specified array is empty. If no array is specified, @ARGV will be used in the mail program and @_ will be used in functions.
Definition: Takes the first element from the specified array and returns that, reducing the array by one element.


@array = (1..5);

while ($element = shift(@array)) {

    print("$element - ");

}

print("\n");

shmctl (ID, CMD, ARG)

Category: Inter-process Communication
Return Value: SCALAR, true if successful; false if not and the undefined value in some cases.
Definition: Controls shared memory.

shmget (KEY, SIZE, FLAGS)

Category: Inter-process Communication
Return Value: SCALAR, the id of a shared memory segment or the undefined value if an error occurred.
Definition: Finds the id of a shared memory segment.

shmread (ID, BUFFER, POS, SIZE)

Category: Inter-process Communication
Return Value: SCALAR, true if successful or false if not.
Definition: Reads information from a shared memory segment.

shmwrite (ID, BUFFER, POS, SIZE)

Category: Inter-process Communication, Shared Memory
Return Value: SCALAR, true if successful or false if not.
Definition: Writes information from a shared memory segment.

shutdown (SOCKET, HOW)

Category: Socket
Return Value: SCALAR, true if successful or false if not.
Definition: Shuts down the connection to a socket. If HOW = 0, all incoming information will be ignored. If HOW = 1, all outgoing information will stopped. If HOW = 2, then both sending and receiving is disallowed.

sin ([EXPR])

Category: Math
Return Value: SCALAR, the sine of EXPR in radians or the sine of $_ if no expression was specified.
Definition: Calculates the sine of the expression in radians.


$temp = sin(4);

sleep ([NUM_SECONDS_TO_SLEEP])

Category: Process, UNIX
Return Value: SCALAR, the number of seconds spent sleeping.
Definition: Causes the current process to sleep for the number of seconds specified (if none specified it sleeps forever, but may be woken up by a SIGALRM signal if this has been programmed).


sleep(5);

socket (SOCKET, DOMAIN, TYPE, PROTOCOL)

Category: Socket
Return Value: SCALAR, true if successful or false if not.
Definition: Opens a specific type of socket.

Tip
When using socket(), make sure that you have the statement use Socket; at the top of your file so that the proper definitions get imported.

socketpair (SOCKET1, SOCKET2, DOMAIN, TYPE, PROTOCOL)

Category: Socket
Return Value: SCALAR, true if successful or false if not.
Definition: Creates an unnamed pair of the specified type of sockets in the specified domain.

sort ([SUBNAME | BLOCK], LIST)

Category: Array
Return Value: ARRAY, a copy of LIST in sorted order.
Definition: Sorts the specified list. Since a copy of the original list is sorted, you must assigned the returned array to a variable in order to save the sorted order. The sort method can be specified with the optional function or block parameter. A function may be specified which takes two arguments (passed as the variables $a and $b) and returns true if the first is less than or equal to the second by any sort of criteria used. Similarly a code block can be specified (effectively an anonymous function) to perform this function. The default sort order is based on the standard string comparison order. You can look at the web page http://www.perl.com/perl/everything_to_know/sort.html for an extensive discussion of sorting techniques.


@array = ("z", "w", "r", "i", "b", "a");

print("sort() ", sort(@array), "\n");

splice (ARRAY, OFFSET, [LENGTH], [LIST])

Category: Array
Return Value: ARRAY, a list of the elements removed from ARRAY.
Definition: Removes the specified elements (LENGTH elements starting at OFFSET) from the specified array, replacing them with the elements in LIST if needed. If no length is specified all the items from offset to the end of the array are removed.


# Replace the first three elements with capitalized 

# versions.

@array        = ("a", "e", "i", "o", "u");

@removedItems = splice(@array, 0 , 3, ("A", "E", "I"));

split ([/PATTERN/], [EXPR], [LIMIT])

Category: Array, Regular Expression
Return Value in Scalar Context: Not recommended, but it returns the number of fields found and stored the fields in the @_ array.
Return Value in Array Context: A list of fields found in EXPR or $_ if no expression is specified.
Definition: Splits a string expression into fields based on the delimiter specified by PATTERN. If no pattern is specified whitespace is the default. An optional limit restricts the number of elements returned. A negative limit is the same effect as no limit. This function is often used in conjunction with join() to create small text databases.


@fields = split(/:/, "1:2:3:4:5");

sprintf (FORMAT, LIST)

Category: String
Return Value: SCALAR, a formatted text string.
Definition: Uses format specifiers to format the elements of LIST in specific ways.


$text = sprintf("%0d \n", 9);

sqrt ([EXPR])

Category: Math
Return Value: SCALAR, the square root of EXPR or $_ if no expression is specified.
Definition: Calculates square roots.


$result = sqrt(4);

srand ([EXPR])

Category: Math
Return Value: None.
Definition: Sets the seed used by the pseudo random number generation algorithm when generating random numbers via rand(). In order to randomize the possible sequences the seed should be set to a different value each time the script is called. When no expression is supplied the default behavior is to use the current system time. This is not a secure method of randomizing for scripts which needs to be secure as it is possible to predict what sequence the script will return.

Tip
It is possible to generate exactly the same data repeatedly (without having to save the entire sequence) simply by setting and saving the seed. Restoring the seed and calling rand() will then produce the same sequence again.


srand(26);

print("Here's a random number:        ", rand(), ".\n");

srand(26);

print("Here's the same random number: ", rand(), ".\n");

stat (FILEHANDLE | EXPR)

Category: File
Return Value: ARRAY, ($device, $inode, $mode, $nlink, $uid, $gid, $rdev, $size, $atime, $mtime, $ctime, $blksize, $blocks).
Definition: Returns the file statistics of the file pointed to by the file handle (or a filename produced by evaluating expression). Note that, like the filetest operators, stat() can use the special underscore filehandle (_) which means that the test is carried out on the same filehandle as the last filetest, stat() or lstat() call.


($device, $inode, $mode, $nlink, $uid, $gid, $rdev, $size, 

    $atime, $mtime, $ctime, $blksize, $blocks) = stat("/etc/passwd");



print("stat() $device, $inode, $ctime\n");

study ([SCALAR])

Category: Regular Expression
Return Value: None.
Definition: Sets up internal lookup tables based on the string studied so that pattern matching operations can use this information to process the pattern match more quickly. 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 specified the $_ is studied by default. Only one string at a time can be studied (subsequent calls effectively forget about the previously studied string). Thus is often used in a loop processing, where each line of a file is studied before being processed with various pattern matches.

substr (EXPR, OFFSET, [LEN])

Category: String
Return Value: SCALAR, a substring of EXPR.
Definition: Gets a substring from EXPR, starting from OFFSET for LEN characters or until the end of the specified string. 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.


$temp = substring("okay", 2);

symlink (OLDFILE, NEWFILE)

Category: File, Symbolic Link
Return Value: SCALAR, true if successful or false if not.
Definition: Creates a symbolic link from the existing file to the new file.


symlink("/usr/local", "/tmp/symlink_to_usr_local");

syscall (LIST)

Category: Miscellaneous, UNIX
Return Value: None.
Definition: Lets Perl call corresponding UNIX C system calls directly. It relies on the existence of the set of Perl header files syscall.ph which declared 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 first 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.


require(""syscall.ph");

syscall(&SYS_getpid);

sysopen (FILEHANDLE, FILENAME, MODE, [PERMISSIONS])

Category: File
Return Value: SCALAR, true if successful or false if not.
Definition: Open a file using the underlying operating system's open() function. The values for MODE and PERMISSIONS are system-dependent. You may be able to look in the Fcntl module for more information.

sysread (FILEHANDLE, BUFFER, LENGTH, [OFFSET])

Category: File, Input
Return Value: SCALAR, the number of bytes read or the undefined value if an error occurred.
Definition: Tries to read LENGTH bytes into BUFFER. The OFFSET parameter is used to change where in the file the data is read.

Caution
This function, along with syswrite(), bypasses the standard low-level input/output functions that other Perl functions use. Therefore, sysread() and syswrite() should be mixed with other types of input and output functions.

system (LIST)

Category: Process
Return Value: SCALAR, the exit code of the system command that was executed.
Definition: Executes LIST as an operating system call. The process to execute this command is forked and the script waits for the child process to return.

Note
To capture the output from a system call use a back-quoted string instead of system().


system("ls -F /var > /tmp/t.tmp");

syswrite (FILEHANDLE, BUFFER, LENGTH, [OFFSET])

Category: File, Output
Return Value: SCALAR, the number of bytes written or the undefined value if an error occurred.
Definition: Tries to write LENGTH bytes from BUFFER. The OFFSET parameter is used to change where in the file the data is written.

Caution
This function, along with syswrite(), bypasses the standard low-level input/output functions that other Perl functions use. Therefore, sysread() and syswrite() should be mixed with other types of input and output functions.

tell ([FILEHANDLE])

Category: File
Return Value: SCALAR, the current position in the file associated with FILEHANDLE or in the last file accessed if no filehandle is specified.
Definition: Gets the current position in a file.


$filePos = tell(FILE);

telldir (DIRHANDLE)

Category: Directory
Return Value: SCALAR, the current position in the directory associated with DIRHANDLE.
Definition: Gets the current directory position. This value can only be used by the seekdir() function.


opendir(DIR, "/tmp");

readdir(DIR);

print("telldir() ", telldir(DIR), "\n");

tie (VARIABLE, PACKAGENAME, LIST)

Category: Miscellaneous
Return Value: SCALAR, a reference to an object.
Definition: Binds a variable to a package class. The creates an instance of this class using the classes' new() method. Any parameters for the new() method may be specified in LIST.

The behavior 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 implementation behind a simple interface. For example, the records in a database can be accessed by looking at the associative array bound to the database.

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.


use Configure;

$return = tie %c, Configure;

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

tied (VARIABLE)

Category: Miscellaneous
Return Value: SCALAR, a reference to an object previously bound via tie() or the undefined value if VARIABLE is not tied to a package.
Definition: Returns a reference to the object which the variable is an instance of. This is the same object as was returned by the original call to tie() when it was bound.

time ( )

Category: Time
Return Value: SCALAR, the time in seconds since January 1, 1970.
Definition: Gets the current time. You can use gmtime(time()) or localtime(time()) to access the different elements of time-day, month, etc…


$then = time();

# time passes while code is running.

$now = time();

$elaspedTime = $now - $then;

times ( )

Category: Process, UNIX
Return Value: ARRAY, ($usertime, $systemtime, $childsystem, $childuser).
Definition: Gets a list of four elements representing the amount of time used by the current and child processes.


($usertime, $systemtime, $childsystem, $childuser) = times();

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

truncate (FILEHANDLE | EXPR, LENGTH)

Category: File
Return Value: SCALAR, true if successful or false if not.
Definition: Truncates the file referenced by FILEHANDLE or named by EXPR to LENGTH.

uc (EXPR)

Category: String
Return Value: SCALAR, a copy of EXPR with all letters in uppercase.
Definition: Creates a copy of EXPR with all letters in uppercase.


print("uc() ", uc("abcdEF"), "\n");

ucfirst (EXPR)

Category: String
Return Value: SCALAR, a copy of EXPR with the first letter in uppercase.
Definition: Creates a copy of EXPR with the first letter in uppercase.


print("ucfirst() ", ucfirst("abcdEF"), "\n");

umask ([EXPR])

Category: Process, UNIX
Return Value: SCALAR, the old process umask.
Definition: Gets and/or sets the process file mask. Returns the old umask so that it can be stored and restored later if required. If called without any arguments returns the current umask. This is the UNIX mechanism used to modify the permissions of any files created.


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

undef ([EXPR])

Category: Miscellaneous
Return Value: SCALAR, the undefined value.
Definition: Undefines the value of EXPR. The expression may be a scalar, an array or a subroutine (specified with a & prefix).

unlink (LIST)

Category: File
Return Value: SCALAR, the number of files successfully deleted.
Definition: Deletes the files in LIST.


unlink("/tmp/t.tst", "/tmp/t.bak");

unpack (TEMPLATE, EXPR)

Category: Array, String
Return Value in Scalar Context: The first item unpacked from EXPR.
Return Value in Array Context: A list of element produced from EXPR.
Definition: Unpacks data using the same template mechanism as pack() to specify the format of the data in EXPR.

unshift (ARRAY, LIST)

Category: Array
Return Value: SCALAR, the number of elements in ARRAY after LIST has been prefixed to it.
Definition: Adds LIST to the front of ARRAY.


@array = qw(a, b, c);

print("unshift() Array has ", 

    unshift(@array, 1, 2, 3), " elements: @array\n");

untie (VARIABLE)

Category: Miscellaneous
Return Value: None.
Definition: Breaks the binding between a variable and a package.

utime (AccESS_TIME, MODIFICATION_TIME, LIST)

Category: Time
Return Value: SCALAR, the number of files successfully changed.
Definition: Sets the access and modification times of all the files in LIST to the times specified by the first two parameters. The time must be in the numeric format (for example, seconds since January 1, 1970).


utime(time(), time(), "/tmp/t.tst");

values (HASH)

Category: Array, Hash
Return Value in Scalar Context: The number of values and, therefore, the number of entries in HASH.
Return Value in Array Context: All of the values in HASH in no particular order.
Definition: Gets a list of all values in HASH. The returned list is ordered by the internal storage requirements, so it is often useful to use the sort() function before processing. For example, sort(values(%hash)).


%hash = ('One' => 1, 'Two' => 2, 'Three' => 3, 'Four' => 4);

print("keys() ", join("-", values(%hash)), "\n");

vec (EXPR, OFFSET, NUM_BITS)

Category: String
Return Value: SCALAR, the value of the bit field specified by OFFSET.
Definition: Uses the string specified EXPR as a vector of unsigned integers. The NUMBITS parameter 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 ^.


$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, UNIX
Return Value: SCALAR, the process id of the child process that just ended or -1 if there are no child processes.
Definition: Waits for a child process to end.

waitpid (PID, FLAGS)

Category: Process, UNIX
Return Value: SCALAR, the process id of the child process that just ended or -1 if there is no such process.
Definition: Waits for a specified child process to end. The flags can be set to various values which are equivalent to those used by the waitpid() UNIX system call. A value of 0 for FLAGS should work on all operating systems that support processes.

wantarray ( )

Category: Miscellaneous
Return Value: SCALAR, true if the currently executing function is looking for a list value or false if it is looking for a scalar value.
Definition: Used to return two alternatives from a subroutine, depending on the calling context. You can use wantarray() inside functions to determine the context in which your function was called.


sub foo {

    return(wantarray() ? qw(A, B, C) : '1');

}



$result = foo();    # scalar context

@result = foo();    # array context



print("foo() in a  scalar context: $result\n");

print("foo() in an array  context: @result\n");

warn ([LIST])

Category: Output
Return Value: None.
Definition: Prints LIST to STDERR, like die(), but doesn't cause the script to exit or raise an exception. 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 continue after a warn().


warn("Unable to calculate value, using defaults instead.\n");

write ([FILEHANDLE | EXPR])

Category: File, Output
Return Value: None.
Definition: Writes a formatted record to the file handle (or the file handle which 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 a format statement. 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 $~ special variable.