|
 |
 |
To access the contents, click the chapter and section titles.
Perl CGl Programming: No experience required.
(Publisher: Sybex, Inc.)
Author(s): Erik Strom
ISBN: 0782121578
Publication Date: 11/01/97
Appendix A Perl Standard Library Reference
- /PATTERN/
- Searches for PATTERN, which must be a regular expression, in a string and returns true (1) on a match or false (") otherwise. If no string is tested with the =~ or !~ operators the string $_ is assumed.
The m form is used when some character other than the slash (/) is needed to delimit the pattern. The g parameter makes the search global, matching all the occurrences of PATTERN in the string; o compiles the pattern just once; i makes the search case-insensitive.
Usage: /PATTERN/[g][i][o] or m/PATTERN/[g][i][o]
Example:
if ($str =~ /.*/) # Matches everything
{
print "It matches\n"
}
- abs
- Returns the absolute value of its argument.
Usage: abs (VALUE)
Example:
$var = abs (-1);
- accept
- Accepts an incoming socket connection, just as the accept system call does in UNIX or Winsock. Returns the packed address if it succeeded, FALSE otherwise.
The function is used by network server processes that will accept connections from clients. GENERICSOCKET is a handle returned by the socket function; NEWSOCKET is opened as a handle if the call succeeds.
Usage: accept (NEWSOCKET,GENERICSOCKET)
Example:
if (!$Connect = accept (NEW, HANDLE))
{
die "Connection failed: $!\n";
}
- alarm
- Sends SIGALRM to this process after SECONDS has elapsed. On some machines, the elapsed time may be up to one second less than specified because of how seconds are counted. Only one timer may be counting at once. Each call disables the previous timer. An argument of 0 may be supplied to cancel the previous timer without starting a new one. The returned value is the amount of time remaining on the previous timer.
Usage: alarm (SECONDS)
Example:
alarm (2);
- atan2
- Returns the arctangent of x/y between π and π.
Usage: atan2 (x, y)
Example:
$pi = atan2 (1, 1) * 4;
- bind
- The same as the bind system call in UNIX and Winsock. Binds NAME, which should be a packed address in the correct type for the socket, to SOCKET. Returns true on success, false otherwise.
This function is important in network programming with sockets because it is what associates a socket handle with some place on the network.
Usage: bind (SOCKET, NAME)
Example:
bind (SH, $SocketAddress);
- binmode
- Primarily useful on operating systems that distinguish between text and binary files. Ensures that the file will be read in binary mode, so it should be called immediately after open() and before any operations are performed on the file handle.
binmode has no effect in UNIX, where all lines in text files end in \n. On Windows and other systems where the line-ending sequence is \r\n, the sequence will be translated to \n when its read. Instances of \n will be translated back to \r\n on output.
Usage: binmode (handle)
Example:
open (FP, $TextFile) || die "Unable to open file: $!\n";
binmode (FP);
- bless
- Used in object-based Perl programs. See perlobj.html (in the Win32 Perl package) for more information. bless() tells REF that it is now an object in the CLASSNAME package or the current package if no CLASSNAME is specified.
Usage: bless (REF, [CLASSNAME])
- caller
- Returns the package name, file name, and line number from which it was called in the currently executing subroutine. With an optional EXPRESSION as an argument, caller() goes back EXPRESSION stack frames before the current frame.
Perls DB debugger uses caller() primarily.
Usage: caller (EXPRESSION)
Example:
($Package, $FileName, $LineNo) = caller;
- chdir
- If possible, changes the current working directory to the expression passed as an argument, or the home directory if no argument is given. Returns 1 on success, 0 on failure.
Usage: chdir ([EXPRESSION])
Example:
# Switch to home directory on UNIX
chdir ($ENV{'HOME'});
- chmod
- Specifically intended to change the permission bits on a list of UNIX files. The first member of the list must be an octal number in the form expected by the UNIX command chmod. Returns the number of files successfully changed.
Interestingly, on Windows NT it has the desired effect, even though file and directory permissions take a different form on NT. If a files permissions are set to 000 (no access), the file will become read-only, although the NT permissions dialog box shows no change.
Usage: chmod (LIST)
Example:
# Lets everyone get into your text files.
$NumFiles = chmod (0666, @TextFiles);
- chomp
- Intended to be a safer version of chop(). It removes any line ending that corresponds to the current value of $/ and returns the number of characters removed. Its often used to remove the newline from the end of an input record when theres a possibility that the final record may be missing its newline. If the argument is omitted, it chomps $_.
With a list as the argument, each element is chomped, and the total number of characters removed is returned.
Usage: chomp (VARIABLE)
Example:
$string = <FP>;
chomp ($string);
- chop
- Removes the last character from a string and returns the character. If the argument is omitted, $_ is chopped. If the argument is a list, each element is chopped and the number of characters removed is returned.
The function usually is used to remove newlines from input records; most sources say chop() is more efficient than the equivalent substitution operation s/\n$//. On Windows systems, chop() is smart enough to remove both the \r and the \n at the end of a text line.
Usage: chop (VARIABLE)
Example:
@BunchaLines = <TF>;
$lines = chop (@BunchaLines);
print "$lines were chopped\n";
- chown
- Changes the owner and group of a list of files. The first two members of the list must be the numeric user ID and group ID. Returns the number of files successfully changed.
If you want to change just the owner and not the group, use 1 as the second element in the list.
Usage: chown (LIST)
Example:
$Files = chown $UID, $GID, "file1", "file2", "file3";
print "$Files successfully changed\n";
- chr
- Returns the character represented by its numeric argument in the current character set, which should be ASCII.
Usage: chr (NUMBER)
Example:
$B = chr (66); # $B now equals "B" in ASCII.
- chroot
- Changes the root directory for the currently running program to its argument, if possible. If the call is successful, the argument to chroot() will become the start of all paths beginning with /.
On UNIX systems, only the super user is allowed to use this function.
Usage: chroot (DIRECTORY)
Example:
$NewRoot = "/usr/ken/bin";
chroot ($NewRoot);
- close
- Closes an open file handle, pipe, or network socket. Note that open() implicitly closes any open handles passed to it before reopening them, though open() does not reset the line counter ($.), as an explicit call to close() would.
If you close a pipe, it will wait for the program running on the pipe to finish.
Usage: close (HANDLE)
Example:
open (FP, "Text.txt");
.
. # Do stuff with FP.
.
close (FP);
- closedir
- Closes a directory handle obtained from opendir().
Usage: closedir (DIRECTORY)
Example:
opendir (DIR, "/usr/textfiles/bob");
closedir (DIR);
- connect
- The same as the connect() function in UNIX and Winsock. Attempts to start a conversation with another process that has called accept() and is waiting for a connection.
Returns true if successful, false otherwise. NAME must be a packed address of the correct type for the SOCKET handle.
Usage: connect (SOCKET, NAME)
Example:
connect (SOCK, $address)
|| die "Can't connect with remote host: $!\n";
- cos
- Returns the cosine of its argument, which must be expressed in radians. To convert radians to degrees, multiply by π/180.
Usage: cos (EXPRESSION)
Example:
$Angle = cos ($Theta);
- crypt
- Works in the same way as the crypt() function on UNIX. crypt() is useful for encrypting strings such as passwords. It can also be used to verify a plain-text password with the encrypted version. In theory, you could encrypt an entire file, but because there is no way to decrypt it, this probably wouldnt be useful.
Returns the encrypted version of TEXT based on SALT.
Usage: crypt (TEXT, SALT)
Example:
$Text = "password";
$EncPwd = crypt ($Text, ""); # Encrypt a password.
if (crypt ("password", $EncPwd) eq $EncPwd)
{
print "They match!\n";
}
- dbmclose
- Superseded by the untie() function. Breaks the binding between a DBM file and an associative array.
Usage: dbmclose (ARRAY)
Example:
dbmclose (%Records);
- dbmopen
- Superseded by the tie() function. Binds a dbm, ndbm, sdbm, gdbm, or Berkeley DB file to an associative array.
Usage: dbmopen (ARRAY, NAME, MODE)
Example:
dbmopen (%STUFF, "Parts.dbm", 0666);
- defined
- Returns a Boolean value indicating whether its argument has a defined value or not. Many operations return the undefined value under conditions such as end of file, uninitialized variable, and system error. This function distinguishes between an undefined null scalar and a defined null scalar with operations that might return a real null string, such as referencing elements of an array. You can also see if arrays or subroutines exist.
Remember that the number 0 and the null string are real values.
Usage: defined (EXPRESSION)
Example:
print if defined $stuff{ÔA'};
- delete
- Removes the specified value from an associative array and returns the value if successful. The undefined value is returned if the function fails.
You can modify the environment with delete().
Usage: delete $ARRAY{KEY}
Example:
delete $ENV{ÔHOME'}; # Remove home directory path from environment.
- die
- Prints its argument list to the standard error output (STDERR) and exits the script with the current error value in $!. If no argument list is given, die() prints the string Died by default.
If used within eval(), the $@ variable is set to the error message and the eval() is aborted with the undefined value.
If the argument list does not end with a newline character, die() appends the script file name, the line number, and the input line number (if there is one) to the message and ends it with a newline. The file name and line number are also available in the tokens __FILE__ and __LINE__.
Usage: die (LIST)
Example:
open (FP, "file.txt")
|| die "Can't open file: $!\n";
- do
- Takes a code block (enclosed in {} braces), a subroutine, and a list or a file name as its arguments.
In its block form, do executes the code within the block and returns the value of the last command. It is usually used in a loop where the conditional is tested at the bottom. The subroutine form is an alternative to &subroutine (list); it executes a subroutine declared by sub and returns the value of the last expression in it. The file name form executes the file given as an argument. This form was commonly used to include library files but has been largely superceded by require.
Usage: do BLOCK, do SUB (LIST), do EXPRESSION
Example:
do # Execute code block.
{
stuff;
}
do stuff (var1, var2); # Execute subroutine.
do "lib.pl"; # Include library file.
- dump
- Causes the memory core to be dumped into a file for perusal by the UNIX utility undump.
dump() takes a label as its argument. When the core dump is executed by undump, it will begin by doing a goto LABEL. If no argument is given, it will begin at the top of the program.
This function is meaningless on Windows 95 and NT.
Usage: dump LABEL
Example:
# Execute code to do other things
.
.
.
dump BYPASS if $ARGV[0] eq "-dump";
BYPASS:
# Execute some other code
.
.
.
- each
- Returns an array whose two members are the key and value of the next entry in an associative array. The function is iterative, so a call to each() usually is used in some kind of loop construct that iterates through the array until each() returns FALSE, signaling that theres nothing left in the associative array. The next call to each() starts over.
There is a single iterator object for each associative array, shared by every call to each(), keys(), and values() in the script. Also, the array should not be changed while using any of these iterative functions.
Usage: each (ARRAY)
Example:
while ($key, $value) = each (%AssociativeArray)
{
print "$key equals $value\n";
}
- eof
- Returns 1 if the next read on a file handle has reached the end of the file, or if the file hasnt been opened.
Perl usually returns an undefined value when the end of a file has been reached, so there is little reasonusuallyto rely on eof() for this information.
The function returns the end-of-file status for the last file read if no argument is given.
Usage: eof (HANDLE), eof
Example:
while (<>)
{
if (eof ())
{
print "Unexpected EOF reached\n";
}
}
- eval
- Parses and executes the expressionwhich could be a block of codein the context of the current program.
Any syntax errors, runtime errors, or die() statements cause eval() to return an undefined value, and $@ is set to the error message. Conversely, if there are no errors, $@ will be null.
Without an argument, eval() evaluates $_.
The function is commonly used in Perl for exception handling.
Usage: eval (EXPRESSION)
Example:
# A Perl shell.
while (<>)
{
eval;
print $@;
}
- exec
- Similar to the exec() family of functions in the C standard library. This function terminates the current Perl program and attempts to run the first argument to exec() with any subsequent arguments passed along to the program being run.
Normally, the function will not return a value. If it does, it means there was an error. Check $! to see why the function failed.
Usage: exec (LIST)
Example:
$shell = "cmd.exe";
exec $shell "notepad.exe"
|| die "exec() failed: $!\n";
- exit
- Exits the current Perl script with its argument as the exit status. If no argument is given, the function exits with status 0.
Keep in mind that exit() cant be trapped if, for example, you want to abort a particular block of code within an eval(). Use die() for that purpose.
Usage: exit (EXPRESSION)
Example:
$failed = -1;
if ($flag == FALSE)
{
$status = $failed;
}
else
{
$status = 0;
}
exit ($status);
- exp
- Returns e, the base of natural logarithms, raised to the power of the argument passed to the function. If no argument is given, $_ is used.
Usage: exp (EXPRESSION)
Example:
$LogN = exp ($LogA);
- fcntl
- Analogous to fcntl() in the C standard library, which is used for file control, hence its name.
The definitions for the function usually are in fcntl.ph and have to be included in the Perl script with use or require.
The function takes three arguments: a file handle, a function, and a scalar value.
On machines that dont implement the UNIX file control functions, fcntl() produces a fatal error.
Usage: fcntl (HANDLE, FUNCTION, SCALAR)
Example:
require "sys/fcntl.ph";
$flags = fcntl (FP, $F_GETFL, 0);
- fileno
- Returns the numeric file descriptor for a file handle. In C programming, the analogous function is used to get numeric handles for files opened as streams with fopen(). In Perl, fileno() is used to construct bitmaps for the select() function.
Usage: fileno (HANDLE)
Example:
open (FP, "stuff.txt")
|| die "Can't open file: $!\n";
$num = fileno (FP);
- flock
- Performs the same operation as flock() in the UNIX C standard library, which is to apply or remove an advisory lock on an open file handle. The function takes a handle and an operation as arguments.
Perl equivalents to the valid flock() operations are:
$LOCK_SH = 1; # Shared lock.
$LOCK_EX = 2; # Exclusive lock.
$LOCK_NB = 4; # Don't block when locking.
$LOCK_UN = 8; # Unlock.
-
-
The function will fail if it is used on systems that dont implement flock().
Usage: flock (HANDLE, OPERATION)
Example:
-
flock (FP, $LOCK_SH);
- fork
- Spawns a child process exactly as the C standard library function does. The childs process ID is returned to the parent and 0 is returned to the child.
Unlike exec(), the parent program continues running while the child does whatever its supposed to do.
Usage: fork
Example:
if ($PID = fork) # $PID is child's process ID.
{
print "This is the parent process\n";
}
elsif (defined $PID) # It's 0 here if it's defined.
{
print "This is the child process\n";
}
- getc
- Returns the next character read from the file handle passed to it. A null string is returned at EOF.
- getc() commonly is used to read from the standard input, STDIN, which it assumes with no argument. It is very slow.
Usage: getc (HANDLE)
Example:
while (!eof)
{
$char = getc;
}
- getgrent
- Along with setgrent() and endgrent(), manipulates login names of groups members on the system.
These functions are specific to UNIX. They are not implemented on Windows 95 or NT versions of Perl.
Usage: getgrent
Example:
setgrent;
while (($name, $pwd, $groupID, $mems)
= getgrent)
{
print "Name = $name\n";
}
- gethostbyaddr
- Translates a packed network address to its more human-readable names and alternate addresses.
This function is used to look up host names and other network information when the only thing you have is an IP address. It returns a list consisting of:
($name, $alias, $addrtype, $length, @addresses)
-
-
where $name is the name associated with the IP address, $alias is any aliases to $name, $addrtype is the network address type, $length is the address length and @addresses is a list of packed IP addresses.
Usage: gethostbyaddr (ADDRESS, TYPE)
Example:
$PackedAddress = pack ("C4", $IPAddr);
($name, $alias, $addrtype, $length, @addresses)
= gethostbyaddr ($PackedAddress, 2);
- gethostbyname
- Similar to gethostbyaddr() above, except a host name is used as the argument. The same information is returned.
Usage: gethostbyname (NAME)
Example:
$Host = "stuff.com";
($name, $alias, $addrtype, $length, @addresses)
= gethostbyname ($Host);
@IP = unpack ("C4", $addresses[0]);
$HostIP = join (".", @IP);
- gethostent
- Used along with sethostent (STAYOPEN) and endhostent() to iterate through the hosts file on your system, returning the same list described in gethostbyaddr(), one at a time, for each entry.
Be advised that if your system is running a name server, you will interrogate the Internet with gethostent(). It will take a long time.
Usage: gethostent
Example:
sethostent (1);
while (($name, $alias, $addrtype, $length, @addresses)
= gethostent)
{
print "$name\n";
}
endhostent;
- getlogin
- Returns the current login name. If the function returns null, the practice on UNIX is to call getpwuid(). However, getlogin() is the only one of the two functions that is implemented on Windows 95 and NT.
Usage: getlogin
Example:
$name = getlogin;
print "$name is signed on\n";
- getnetbyaddr
- Translates a packed network address to its network name or names.
The function returns a list of information similar to that returned by gethostbyaddr(), etc.
($name, $alias, $type, $network)
-
-
where $name is the network name, $alias is any aliases to it, $type is the address type, and $network is the packed network address.
Usage: getnetbyaddr (ADDRESS, TYPE)
Example:
$AF_INET = 2;
($name, $alias, $type, $network)
= getnetbyaddr ($address, $AF_INET);
- getnetbyname
- Identical to getnetbyaddr(), except it takes a network name as its argument.
Usage: getnetbyname (NAME)
Example:
($name, $alias, $type, $network)
= getnetbyaddr ($name);
- getnetent
- Similar to the gethostent() functions. getnetent(), setnetent (STAYOPEN), and endnetent() are used to iterate through the current list of networks, returning a list in the form described for getnetbyaddr() above.
Usage: getnetent
Example:
$STAYOPEN = 1;
setnetent ($STAYOPEN);
while (($name, $alias, $type, $network)
= getnetent);
{
print "$name\n";
}
endnetent;
- getpeername
- Returns the packed socket address of the other end of a SOCKET connection, which can be unpacked to get the name of the peer. The function takes a socket handle as its argument.
Usage: getpeername (SOCK)
Example:
$addr = "S n a4 x8";
$peer = getpeername (S); # S is a socket handle.
($fam, $port, $peeraddr) = unpack ($addr, $peer);
- getpgrp
- Returns the process group for the process ID passed as an argument. A PID of 0 gets the current process, which also is assumed if no argument is passed.
This function is specific to UNIX. It is not implemented in the Win32 versions of Perl.
Usage: getpgrp (PID)
Example:
$me = getpid;
- getppid
- Returns to process ID of the parent process. On UNIX, the init process has an ID of 1; if your parent process ID turns up with this value, it means the parent has died.
This function is specific to UNIX. It is not implemented in the Win32 versions of Perl.
Usage: getppid
Example:
if (getppid == 1)
{
print "Parent process has died\n";
}
- getpriority
- Returns the scheduling priority of a process, process group, or user, taking arguments WHICH and WHO, where WHICH indicates a process, group, or user ID and WHO is interpreted from WHICH (0 is the current pro-cess, group, or user).
This function is specific to UNIX. It is not implemented in the Win32 versions of Perl.
Usage: getpriority (WHICH, WHO)
Example:
$CurPriority = getpriority ($PRIO_PROCESS, 0);
- getprotobyname
- Translates a network protocol name into its number in a fashion similar to the getnetby and gethostby functions.
The function returns a list of three items:
($name, $alias, $proto)
-
-
where $name is the protocol name, $alias is any aliases to $name, and $proto is the protocol number.
Usage: getprotobyname (NAME)
Example:
($name, $alias, $proto) = getprotobyname ($ProtoName);
- getprotobynumber
- Translates a protocol number to its name. Identical in all other respects to getprotobyname().
Usage: getprotobynumber (NUM)
Example:
($name, $alias, $proto) = getprotobynumber ($ProtoNumber);
- getprotoent
- Used with setprotoent (STAYOPEN) and endprotoent() to iterate through the list of protocols, returning the list described in getprotobyname() above.
Usage: getprotoent
Example:
$STAYOPEN = 1;
setprotoent ($STAYOPEN);
while (($name, $alias, $proto) = getprotoent)
{
print "Name = $name\n";
}
endprotoent;
- getpwent
- Used with setpwent() and endpwent() to iterate through the system password file, returning a list that corresponds with the UNIX passwd structure. See the UNIX man page entry for getpwent(3) for details.
This function is specific to UNIX. It is not implemented in the Win32 versions of Perl.
Usage: getpwent
Example:
setpwent;
while (@PWD_ENTRY = getpwent)
{
.
. # Do something with the entry.
.
}
endpwent;
- getpwnam
- Returns the same listcorresponding to a UNIX passwd structurethat is sent back with each call to getpwent() above. See the UNIX man page entry for getpwnam (3) for details. The function takes a user name as its argument.
This function is specific to UNIX. It is not implemented in the Win32 versions of Perl.
Usage: getpwnam (NAME)
Example:
@PWD_ENTRY = getpwnam ($name);
- getpwuid
- Returns the same list described in getpwnam() above, using a user ID number as its argument.
This function is specific to UNIX. It is not implemented in the Win32 versions of Perl.
Usage: getpwuid (IDNUM)
Example:
@PWD_ENTRY = getpwuid ($UserID);
- getservbyname
- Translates a serviceor network portname into its number, with a protocol name (such as tcp or udp) as its second argument.
The function returns a list consisting of these values:
($name, $alias, $port, $proto)
-
-
where $name is the service name, $alias is any aliases to $name, $port is the port number, and $proto is the protocol.
Usage: getservbyname (NAME, PROTOCOL)
Example:
$prot = "tcp";
$serv = "ftp";
($name, $alias, $port, $proto)
= getservbyname ($serv, $prot);
- getservbyport
- Takes a service port number as its first argument; identical to getservbyname() in all other respects.
Usage: getservbyport (PORTNUM, PROTOCOL)
Example:
$prot = "tcp";
$serv = 23;
($name, $alias, $port, $proto)
= getservbyport ($serv, $prot);
- getservent
- In combination with setservent (STAYOPEN) and endservent(), iterates through the list of network services, returning the list described in getservbyname() above for each entry.
Usage: getservent
Example:
$STAYOPEN = 1;
setservent ($STAYOPEN);
while (($name, $alias, $port, $proto) = getservent)
{
print "Name = $name\n";
}
endservent;
- getsockname
- Returns the packed address of the socket handle opened at this endthe other side of getpeername().
Usage: getsockname (SOCK)
Example:
$addr = "S n a4 x8";
$this = getsockname (S); # S is a socket handle.
($fam, $port, $thisaddr) = unpack ($addr, $this);
- getsockopt
- Returns the socket option requested. Undefined on error. See the UNIX man page for getsockopt (3) for many, many details.
See also the Win32 documentation for Winsock.
Arguments to getsockopt() are SOCK (the socket handle), LEVEL (the protocol number), and NAME (the option name).
Usage: getsockopt (SOCK, LEVEL, NAME)
Example:
$opt = getsockopt (SOCK, $ProtoNum, $Option);
- gmtime
- Converts the integer, seconds-since-epoch value returned by time(), to an array of values corresponding to the C standard library tm structure (see time.h) corrected for Greenwich Mean time, or UTC.
The array contains nine values:
($secs, $mins, $hour, $mday, $mon, $year, $wday, $yday, $isdst)
-
-
which are interpreted as follows:
- $secs Seconds from the hour
- $mins Minutes from the hour
- $hour Hours from midnight
- $mday Day of the month (131)
- $mon Month of the year (011)
- $year Years from 1900
- $wday Day of the week (06)
- $yday Day of the year (0365)
- $isdst Non-zero if daylight savings time
-
-
With no argument, the function evaluates the current time. In a scalar context, gmtime() loads the variable with a string similar to that returned by the C standard library function ctime(), for example:
Sat Sep 13 13:39:32 1997
-
-
Usage: gmtime (EXPRESSION)
Example:
$TimeNow = time;
($secs, $mins, $hour, $mday, $mon, $year, $wday, $yday, $isdst)
= gmtime ($TimeNow);
- goto
- Jumps to the point in the Perl script where it finds a statement corresponding to its LABEL argument and resumes execution there. Never returns a value.
This function can only jump to labels in the main body of the program, outside of do blocks.
Programming purists have maintained for years that the goto statement is actually harmful because it allows the programmer to jump around anywhere in the code without regard for modular coding styles. Others regard this aversion to goto as so much nonsense. The debate will rage on; in any event, theres a good chance that goto will be changed or removed in a future version of Perl, so its probably a good idea not to use it at all.
Usage: goto LABEL
Example:
while (<>)
{
.
.
.
if ($_ eq "stop")
{
goto OUTSIDE;
}
}
OUTSIDE:
- grep
- Evaluates the expression in its first argument for instances of each element in the list that is its second argument, returning an array of matches.
grep() is named forand works in essentially the same way asthe workhorse utility from UNIX that has found its way into many other platforms, including Windows 95 and NT.
If the result is placed in a scalar variable rather than a list, it will hold the number of matches.
Usage: grep (EXPRESSION, LIST)
Example:
$times = grep (/"Now is"/, $string);
- hex
- Returns the decimal value of its argument, which is interpreted as a hexadecimal string. In the absence of an argument, $_ is interpreted.
Usage: hex (EXPRESSION)
Example:
# Set $num to 65,535.
$num = hex ("ffff");
- index
- Returns the first position in a string where the specified substring occurs, starting from position 0 in the string or, optionally, from a specified position. Alternatively, the starting position can be set in $[.
If the substring is not found, index() returns the starting position minus 1 (1 in the default case, because thats one less than 0).
Usage: index (STRING, SUBSTRING, [POSITION])
Example:
$StartPos = 10;
$found = index ($string, "whatever", $StartPos);
if ($found < $StartPos)
{
print "Couldn't find it\n";
}
- int
- Returns the integer portion of the expression passed as its argument. As usual, $_ is evaluated in the absence of an argument.
The function is useful in scripts that need to do integer division. Even if a variable holds an integer value, by default Perl does floating-point divisions unless the variables have been explicitly cast to integers.
Usage: int (EXPRESSION)
Example:
# Need integer result.
$result = int ($a) / int ($b);
- ioctl
- Implements the UNIX ioctl() function for controlling devices. See the man pages for ioctl(2). You may have to require ioctl.ph.
The scalar first argument will be read and/or written depending on the function in the second argument, and a pointer to the string value of the scalar third argument will be passed as the third argument of the actual ioctl call. (If the third argument is a number rather than a string, its value will be passed rather than a pointer to the string value. To guarantee this to be true add a 0 to the scalar before using it.)
The pack() and unpack() functions can be used to manipulate the values of structures used by ioctl().
This function is very system-specific and should not be considered portable.
Usage: ioctl (HANDLE, FUNCTION, SCALAR)
Example:
$result = ioctl (FP, $ControlFunction, $Arg);
- join
- Concatenates the array of strings in its second argument into a single string of fields separated by the expression in its first argument. This function is the opposite of split().
Usage: join (EXPRESSION, LIST)
Example:
$hour = "9";
$min = "27";
$sec = "55";
$time = join (":", $hour, $min, $sec);
- keys
- Returns an array of all of the keys of the associative array passed to it. Associative arrays are hashed for more efficient searching and storage, so the keys probably wont be returned in the order in which they were entered.
This function returns every key in the associative array, which can get cumbersome if the array is large. In such a case, use the each() function, which iterates through the array.
Usage: keys (ASSOCIATIVE_ARRAY)
Example:
# Sort the keys.
foreach $key (sort (keys %BigArray))
{
print "$key = $BigArray{$key}\n";
}
- kill
- Performs the same function as the UNIX C standard library kill(), which is to send a signal to a list of processes. The first member of the list is the signal value.
It returns the number of processes that were signaled successfully.
This function is specific to UNIX. It is not implemented in the Win32 versions of Perl.
Usage: kill (LIST)
Example:
# Poleax a process.
$result = kill (9, 256);
if ($result)
{
print "Process #256 has died\n";
}
- last
- Breaks out of a conditional loop before the termination condition is satisfied. The function does the same as the break statement in the C programming language.
An optional LABEL argument causes processing to jump to LABEL.
Usage: last [LABEL]
Example:
while ($x < $y)
{
$x++
if ($x == $z)
{
last;
}
}
- lc
- Lowercases the string passed to it.
Usage: lc (EXPRESSION)
Example:
$str = "NOW IS THE TIME";
print lc ($str), "\n"; # Prints "now is the time".
- lcfirst
- Lowercases the first character of the string passed to it.
Usage: lcfirst (EXPRESSION)
Example:
$str = "NOW IS THE TIME";
print lcfirst ($str), "\n"; # Prints "nOW IS THE TIME".
- length
- Returns the length (in characters) of the expression passed to it. With no argument, the $_ variable is evaluated.
Usage: length (EXPRESSION)
Example:
$string = "Now is the time for all good people etc."
$len = length ($string);
- link
- Creates a new file name that is linked to the name of the old file, but doesnt create another file. Returns 1 for success or 0 for failure.
This is standard practice in UNIX, and the function conforms to the link() function in the UNIX C standard library. However, link() has no analog on Windows 95 and NT; the function is not implemented in the Win32 versions of Perl.
Usage: link (OLDNAME, NEWNAME)
Example:
if (link ("stuff", "stuff1"))
{
print "Link created successfully\n";
}
- listen
- Analogous to the UNIX sockets and Winsock listen() function. Tells the system that you will accept up to QUEUESIZE connections on the specified socket handle. You then pass the socket to accept() to wait for a connection request.
The function returns true if successful, false on failure, with the error code in $!.
UNIX documentation specifies no limit to QUEUESIZE. The limit in Winsock is 5.
Usage: listen (HANDLE, QUEUESIZE)
Example:
$result = listen (SH, 5);
if ($result)
{
$result = accept (NEWSOCK, SH) # Wait for connect.
}
- local
- Makes the variables in its list local to the block, eval(), or subroutine that encloses them; in other words, they arent visible to other parts of the program.
Note that the newer my() function is considered faster and safer than local(), which is a runtime command and thus is executed every time through a loop. This is wasteful of stack storage.
local() commonly is used to name local variables in a subroutine.
Usage: local (LIST)
Example:
sub Asubroutine
{
local ($x, $y, $z); # Declare local variables.
.
.
.
}
- localtime
- Converts the integer time value returned by time() to an array of time information corrected for the local time zone. See gmtime() for a complete explanation of the array structure and other features.
Usage: localtime (EXPRESSION)
Example:
$TimeNow = time;
($secs, $mins, $hour, $mday, $mon, $year, $wday, $yday, $isdst)
= localtime ($TimeNow);
- log
- Returns the base-e logarithm of the expression passed to it. With no argument, $_ is evaluated.
Usage: log (EXPRESSION)
Example:
$result = log ($var);
- lstat
- Returns the same information as stat(), but on a symbolic link to a file instead of the file itself. See stat() for detailed information.
If symbolic links are not implemented, a normal stat() is done.
Usage: lstat (HANDLE)
Example:
@STAT_BLOCK = lstat (LINK);
- map
- Evaluates a block or expression for each element of an array (locally setting $_ to each element) and returns the list value. Each element of the array may produce zero or more elements in the returned value.
Usage: map (EXPRESSION, LIST)
Example:
@chars = map(chr, @nums);
- mkdir
- Creates a directory with the name of its first argument, if possible, with permissions specified by the second argument, or defaulting to the current umask on UNIX.
Returns 1 on success, or 0 on failure, with the error code loaded into $!.
Usage: mkdir (NAME, [MODE])
Example:
if (mkdir ($NewDir, 0666))
{
print "$NewDir created successfully\n";
}
- msgctl, msgget, msgrcv, and msgsnd
- These functions are specific to the System V UNIX interprocess communication package and are unavailable on any other platform.
For information, see the System V man pages for msgctl (2).
- my
- Declares the listed variables to be lexically local to the enclosing block, subroutine, eval(), or do. If more than one value is listed, the list must be in parentheses. Only alphanumeric identifiers may be lexically scoped; you must use local() with built-in Perl variables such as $_.
Variables declared with my() are completely hidden from the rest of the program, including any subroutines. Even the same subroutine gets its own copy every time its called.
For this reason, my() is considered safer and faster than local().
Usage: my (LIST)
Example:
sub Asubroutine
{
my ($a, $b, $c); # Local variables declared.
.
.
.
}
- next
- Analogous to the continue statement in the C programming language. This function stops execution of the code block within a loop and immediately starts the next iteration. An optional LABEL argument forces execution to begin at the label.
Usage: next [LABEL]
Example:
for ($n = 0; $n < 100; $n++)
{
if ($n == 50) # Skip this one.
{
next;
}
.
.
.
}
- oct
- Returns the decimal value of its argument, which is interpreted as an octal string. If the argument begins with 0x, it will be regarded as a hexadecimal string. With no argument, the function will evaluate $_.
Usage: oct (EXPRESSION)
Example:
$mode = oct (0666);
- open
- Opens the file name passed in its second argument, if possible, and links it with the file handle passed in the first argument. HANDLE can be either a handle name or the result of an expression; in the latter case, the value will be used as the file handle.
The function can open files in these modes, designated by the character in front of the file name:
- < or nothing Input or read-only
- > Output or write-only
- >> Appending; writing starts at EOF
- +< or +> Reading and writing
In addition, a | in front of the file name makes it a command to which output is piped, and a | at the end of the name pipes input back to the Perl script. STDIN is opened with and STDOUT is opened with >-.
Usage: open (HANDLE, [EXPRESSION])
Example:
# Typical read.
open (FP, "stuff.txt");
# Typical write.
open (FP, ">stuff.txt");
# Append with variable.
$filename = "stuff.txt";
open (FP, ">>$filename"); # Still uses quotes.
- opendir
- The first of the directory functions. Opens the directory named in its second argument and links it with the handle in the first argument.
This function is used with readdir(), rewinddir(), telldir(), seekdir(), and closedir(). See each of these functions for individual descriptions.
Usage: opendir (HANDLE, EXPRESSION)
Example:
opendir (DP, "/usr/bin")
|| die "Can't open directory: $!\n";
- ord
- Returns the numeric ASCII value of the first character in its argument.
Usage: ord (EXPRESSION)
Example:
$a = ord ("A"); # $a = 65.
- pack
- Packs an array or list of values into a binary structure based on a template that defines the structure.
The various pack templates are reproduced here.
Character
| Description
|
A
| ASCII string that will be padded with spaces
|
a
| ASCII string, no space padding
|
B
| Bit string, high- to low-order
|
b
| Bit string, low- to high-order
|
C
| An unsigned character
|
c
| A signed character
|
d
| Double-precision floating-point number
|
f
| Single-precision floating-point number
|
H
| Hexadecimal string, high nybble (four bits) first
|
h
| Hex string, low nybble first
|
I
| Unsigned integer
|
i
| Signed integer
|
L
| Unsigned long integer
|
l
| Signed long integer
|
N
| Long integer in network order
|
n
| Short integer in network order
|
p
| Pointer to string
|
X
| Back up a byte
|
x
| NULL byte
|
u
| Uuencoded string
|
@
| NULL-fill to absolute position
|
-
-
Each of the letters can be followed by a number that signifies a repeat count. An asterisk (*) in place of a number tells pack() to take the remaining items in the list.
The opposite of pack() is unpack(), and generally the same templates may be used with it.
Usage: pack (TEMPLATE, LIST)
Example:
# Pack a string.
$str = pack ("a4 a2", "Now ", "is"); # $str = "Now is".
# Pack characters.
$str = pack ("cccc", "e", "f", "g", "h");
# Pack an IP address.
$IP = "127.0.0.1";
@IPS = split (/./, $IP)
$PackedIP = pack ("c4", @IPS);
- pipe
- Opens a pair of connected pipes. Its arguments are file handles.
Usage: pipe (READ, WRITE)
Example:
pipe (READ, WRITE);
if ($pid = fork)
{
close (WRITE);
.
.
.
}
elsif (defined $pid)
{
close (READ);
.
.
.
}
- pop
- Returns the last value of an array, like popping it off of a stack, and shortens the array by one. An undefined value is returned when the array is empty.
Usage: pop (LIST)
Example:
# Array will be empty at the end of the loop.
while (defined ($tmp = pop (@list)))
{
print "$tmp\n";
}
- print
- Prints a string or list of strings separated by commas. Returns 1 on success, 0 on failure, with the error in $!.
If the first argument is a file handle, the output will go there. Otherwise, print()s output goes to the current output handle. Unless you change it with select(), the handle will be STDOUT.
Note that the handle should not be followed by a comma in the argument list. In this example:
print HANDLE, LIST;
-
- the function will output the value of HANDLE to STDOUT.
print() is also the preferred Perl method for writing to files, not write().
Usage: print (HANDLE, LIST)
Example:
print "Now", " is", " the", "\n"; # Display "Now is the".
print FP, "Now is the time"; # Output to file.
- printf
- Prints a formatted list to a file handle or STDOUT. The format string is divided into fields by specifiers in the form %m.nx where m (minimum field length) and n (number of decimal places) are sizes and x is one of the types in the following list of printf format specifiers.
Character
| Description
|
c
| Character
|
d
| Decimal number
|
e
| Exponential floating-point number
|
f
| Fixed floating-point number
|
g
| Compact floating-point number
|
ld
| Long decimal number
|
lo
| Long octal number
|
lu
| Long unsigned decimal number
|
lx
| Long hexadecimal number
|
o
| Octal number
|
s
| String
|
u
| Unsigned decimal number
|
x
| Hexadecimal number
|
-
-
The arguments to printf() are the format string and the list of variables to correspond with the formats.
Usage: printf (FORMAT, LIST)
Example:
$str = "The number is";
$num = 4.001;
# Print "The number is 4.00".
printf ("%s %0.2f\n", $str, $num);
- push
- The functional opposite of pop(). Pushes the values of its second argument, a list, onto the end of the first argument, another list. The recipient list increases by the size of the second argument.
Usage: pop (LIST, LIST)
Example:
# Concatenate two lists.
pop (@list1, @list2);
- rand
- Returns a pseudorandom fractional number between 0 and the value of its argument. The range is 0 to 1 if the argument is omitted.
Use int() to turn the number into an integer.
Usage: rand (EXPRESSION)
Example:
# Roll the dice.
$die = int (rand (6)) + 1; # Add one because it starts at 0.
- read
- Reads a specified number of bytes from a file handle into a scalar buffer. Returns the number of bytes read, or 0 on EOF. The undefined value is returned on error, the code for which is placed in $!.
An optional offset argument tells read() to place its data at some place other than the beginning of the buffer.
Remember that, in Perl, the opposite of read() is print(), not write().
Usage: read (HANDLE, BUFFER, LENGTH, [OFFSET])
Example:
while (read (HANDLE, $buffer, 1024))
{
. # Do something with data in $buffer.
.
.
}
- readdir
- Reads from a directory handle obtained by opendir().
If the result of readdir() is placed in a scalar variable, it will return the next directory entry. In an array context, it will return the rest of the directory. The undefined value returns in the scalar context when there are no more entries to be read; a null list comes back in an array context.
Usage: readdir (HANDLE)
Example:
while ($entry = readdir (HANDLE))
{
print "File = $entry\n";
}
- readlink
- Returns the value of a symbolic link on systems where they are implemented. Windows 95 and NT dont support symbolic links.
On error, the return value is undefined, with the error code in $!. The function uses $_ if the argument is left off.
Usage: readlink (EXPRESSION)
Example:
$link = readlink ($filename);
- recv
- The same as the UNIX sockets and Winsock function. recv() tries to read a specified number of bytes into a buffer from the socket handle passed as the first argument.
An optional FLAGS argument allows recv() to read out-of-band data and to peek at the datathe bytes are read, but not consumed.
The address of the sender is returned on success; the undefined value is the result on error.
Usage: recv (SOCK, BUFFER, LENGTH, [FLAGS])
Example:
if ($SenderIP = recv (SOCK, $buf, 4096))
{
$sent = length ($buf);
.
.
.
}
else
{
die "Receive failed on socket\n";
}
- rename
- Changes the name of a file, if possible. Returns 1 on success, 0 on failure with the error code in $!.
rename() works unconditionally, that is, if a file of the same name exists, it will be overwritten.
The function generally will not work across file systems.
Usage: rename (OLD, NEW)
Example:
rename ("OldStuff.txt", "NewStuff.txt);
- require
- Includes and executes any Perl code in the specified file. Unlike eval(), require() checks to ensure that the file hasnt been included before.
This function can also use the @INC array to search a specified path for files to be included.
require() supercedes the older do EXPRESSION as a method of including external files in a Perl script.
Usage: require (EXPRESSION)
Example:
# Include a header file.
require ("header.pm") || die "Can't open header file: $!\n";
- reset
- Used in a continue block at the end of a loop to clear variables and reset searches so that they work again. The argument is a list of single characters, with ranges specified by hyphens. All variables and arrays beginning with one of the letters are reset to their pristine state. If the expression is omitted, one-match searches are reset to match again.
The function only resets variables or searches in the current package and it always returns 1.
Resetting A-Z is not recommended because youll wipe out @ARGV and @ENV.
Usage: reset (EXPRESSION)
Example:
reset ("x"); # Clears all variables starting with "X".
reset ("a-z); # Clears all lowercase variables.
reset ("A-Z"); # Everything goes.
- return
- Returns from a subroutine with the specified value. Bear in mind that subroutines automatically return the value of the last expression successfully evaluated. This is considered more efficient and faster than an explicit return.
Using return outside of a subroutine is a fatal error.
Usage: return LIST
Example:
sub Asubroutine
{
.
.
.
return 1;
}
- reverse
- When an array is set to the result of this function, it will consist of the elements of the argument list in reverse order.
In a scalar context, the function returns a string of the first characters of the argument list elements in reverse.
reverse() can also be used on associative arrays.
Usage: reverse (LIST)
Example:
@RevList = reverse (@List);
- rewinddir
- Sets the current position in a directory to the beginning for any subsequent readdir() operations on a directory handle obtained from opendir().
Usage: rewinddir (DIR)
Example:
$entry = readdir (DIR);
if (!defined $entry)
{
rewinddir (DIR);
}
- rindex
- Essentially the reverse of index(), in that the function returns the position of the last occurrence of a specified substring in a specified string. Returns $[ - 1 if the substring is not found.
An optional POSITION argument marks the rightmost position that can be returned.
Usage: rindex (STRING, SUBSTRING, [POSITION])
Example:
$pos = rindex ("now me is me the me time", "me"); # $pos = 22.
- rmdir
- Deletes the directory passed as its argument, if possible, returning 1 on success and 0 on failure with the error code in $!.
The directory must be empty for rmdir() to succeed.
Usage: rmdir (EXPRESSION)
Example:
if (!rmdir ($DirName))
{
die "Can't delete $DirName: $!\n";
}
- s
- The substitution operator. Almost identical to /PATTERN/, with two exceptions:
- The slash (/) ending the search string is followed by a replacement string specifying the string with which the first (or all) occurrences of the search string will be replaced.
- An additional optional parameter, e, which tells the function that the replacement string should be treated as an expression, the result of which will be used in the replacement.
Usage: s/SEARCH/REPLACE/[g][i][e][o]
Example:
$str =~ s/\bsoup\b/nuts/g; # Globally replace "soup" with "nuts".
- scalar
- Forces interpretation of its argument as a scalar value.
For example, passing an array to scalar() would return the length of the array.
Usage: scalar (EXPRESSION)
Example:
$len = scalar (@array);
- seek
- The same as fseek() in the C standard library. Positions the file pointer for an open file handle to the specified position relative to the specified offset. The offset values are:
- 0 for the beginning of the file
- 1 for the current position in the file
- 2 for the end of the file
The position argument can be less than 0 for offset values of 1 and 2.
The function returns 1 on success, 0 on failure with the error code in $!.
Usage: seek (HANDLE, POSITION, OFFSET)
Example:
seek (HANDLE, 0, 2); # Position to end of file.
- seekdir
- Analogous to seek() above, but operates on directory handles obtained from opendir(). The function sets the current position in a directory where the next readdir() operation will take place.
The second argument to seekdir() must be a value returned by telldir().
Usage: seekdir (HANDLE, POSITION)
Example:
while ($entry = readdir (DIR))
{
if ($entry eq $seekfile)
{
$BackPos = telldir (DIR);
}
elsif ($entry eq $lastfile)
{
seekdir (DIR, $BackPos)
}
- select
- Comes in two unrelated forms. The firstselect (HANDLE)makes HANDLE the default output for print() and write(). In other words, if no handle is specified for the functions, they will send their output to HANDLE.
Also in this first form of select(), any variables, built-in or otherwise, that refer to output will default to HANDLE.
The second form, select (RBIT, WBIT, EBIT, TIME), directly calls the UNIX select() system function, which is used to synchronize input/output multiplexing. RBIT, WBIT, and EBIT refer to sets of file descriptors to reading, writing, and exceptions, respectively; TIME is a timeout value.
This form is specific to UNIX. For detailed information, see the UNIX man page for select (3).
Usage: select (HANDLE), select (RBIT, WBIT, EBIT, TIME)
Example:
open (FP, ">stuff.txt") # Open for output.
|| die "Can't open file: $!\n";
select (FP); # Now it's STDOUT.
print $stuff; # Goes to the file.
- semctl, semget, and semop
- These functions handle semaphores in the System V UNIX interprocess communications (IPC) library. They are unavail-able on any other platform.
For details, see the System V UNIX man page for semctl (2).
- send
- Implements the UNIX sockets and Winsock send() function in Perl. The function sends data on a network socket. It takes four arguments:
- SOCKET The socket handle to which youre sending
- MESSAGE A scalar buffer containing the data
- FLAGS An optional argument that allows you to send out-of-band data or unrouted data (used for testing only)
- TO (Optional) to send data to an unconnected socket
The function returns the number of characters that were successfully sent, or the undefined value in case of error (with the error code in $!).
Usage: send (SOCKET, MESSAGE, [FLAGS], [TO])
Example:
while ($buffer = <FP>) # Send file over network.
{
$len = send (SOCK, $buffer);
if ($len < length ($buffer))
{
print "Warning: not all data sent\n";
}
}
- setpgrp
- Sets the process group for the process ID passed to it as an argument. This function is specific to UNIX. It is not implemented in the Win32 versions of Perl.
Usage: setpgrp (ID, GROUP)
Example:
setpgrp (0, $$);
- setpriority
- Sets the priority for a process, group, or user. Usually used in tandem with getpriority(), which returns the current priority information.
This function is specific to UNIX. It is not implemented in the Win32 versions of Perl.
Usage: setpriority (WHICH, WHO, PRIO)
Example:
setpriority (0, 0, 0);
- setsockopt
- Provides a method of setting a wide variety of network socket options for UNIX sockets and Winsock from Perl. Returns the undefined value on error.
The fourth argument, which sets the option value, is not always needed; in that case, it may be specified as undef.
The options you may set vary between UNIX and Windows. Consult the Winsock documentation or the UNIX man page for getsockopt (3) for a myriad of details.
Usage: setsockopt (SOCK, LEVEL, OPT_NAME, OPT_VAL)
Example:
setsockopt (SOCK, $IPPORT_SMTP, $SO_KEEPALIVE, undef);
- shift
- Removes the first member of an array and returns it, shortening the array by 1 member and shifting the remaining members down. The function returns the undefined value if the array is empty.
In the absence of an argument, shift() manipulates the @ARGV array in the main program or @_ in subroutines.
See also unshift().
Usage: shift (ARRAY)
Example:
while ($stuff = shift (@BigList))
{
print "Element is $stuff\n";
}
- shmctl, shmget, shmread, and shmwrite
- These functions deal with shared memory in the System V UNIX interprocess communication package (IPC). They are specific to System V UNIX and are not available on any other platform.
For details, consult the System V man pages for shmctl (2).
- shutdown
- Shuts down all or part of a full-duplex socket connection by calling the UNIX sockets or Winsock shutdown() function.
In addition to the socket handle that is its first argument, shutdown() takes a second parameter that specifies how the connection is to be dropped. The HOW parameter can take one of three values:
- 0 No more data can be received.
- 1 No more data can be transmitted.
- 2 Receives and transmissions are disallowed.
Usage: shutdown (SOCK, HOW)
Example:
shutdown (SOCK, 2); # Drop the connection completely.
- sin
- Returns the sine of its argument expressed in radians. With no argument, $_ is evaluated.
Usage: sin (EXPRESSION)
Example:
$rads = sin ($theta);
- sleep
- Suspends the Perl script formore or lessthe number of seconds specified in its argument, or forever if no argument is given. Returns the number of seconds actually passed in sleep.
You can interrupt the sleep with SIGALARM, if your system can send it.
The function may be off by as much as a second on systems that that process a second as it ticks. Imagine a watch hand that revolves once every second: The second is counted at the 12 oclock position. Thus, if sleep (1) is called just before the next second ticks off, the sleep will end at the top of the hour anyway.
Usage: sleep (EXPRESSION)
Example:
sleep (5); # Sleep for five seconds.
- socket
- Opens a network communication socket and associates it with its SOCKET argument by calling the UNIX sockets or Winsock socket() function.
Its arguments are:
- SOCKET The socket handle to be opened
- DOMAIN An address family as defined for your operating system, not an Internet domain name
- TYPE The type of connection desired
- PROTOCOL An optional communication protocol
This function is to TCP/IP network sockets what open() is to files. You cannot perform many network operations without first opening a socket over which to communicate.
Though the function call is the same for both systems, there are UNIX and Winsock specifics that you can use in constructing a socket handle. Consult the Winsock documentation or the UNIX man pages for socket (3).
Usage: socket (SOCKET, DOMAIN, TYPE, PROTOCOL)
Example:
socket (SOCK, $AF_INET, $SOCK_STREAM, 0)
|| die "Can't open socket: $!\n";
- socketpair
- Creates a pair of connected sockets.
The first two arguments are socket handles. Otherwise, the function is identical to socket().
Usage: socketpair (S1, S2, DOMAIN, TYPE, PROTOCOL)
Example:
socketpair (SOCK1, SOCK2 $AF_INET, $SOCK_STREAM, O)
|| die "Can't open sockets: $!\n";
- sort
- Sorts an array, either by standard string comparison order or by the dictates of a subroutine that you supply, and returns the sorted array.
If a subroutine argument is specified, it must be the name of a routine that returns an integer less than 0, 0 or an integer greater than 0. Also, the subroutine will not reference @_, but two variables $a and $b that will be compared to determine the order of the sort.
Usage: sort ([SUB], LIST)
Example:
@SortedArray = sort (@UnsortedArray); # Default sort.
# Sort by subroutine
sub sortem
{
$a <=> $b;
}
@SortedArray = sort sortem @UnsortedArray;
- splice
- Removes the elements between a specified offset and length from an array. Replaces the removed elements with the members of an optional list if it is specified. The array will grow or shrink with the size of the replacement list.
If the length argument is omitted, everything from the offset is removed.
Usage: splice (ARRAY, OFFSET, [LENGTH], [LIST])
Example:
splice (@Dogs, 0, length (@Cats), @Cats); # Replace from
beginning.
- split
- Splits a string into an array of substrings based on the delimiter pattern that is passed in its first argument. The delimiter pattern is removed from the array.
In a scalar context, this function returns the number of fields found and the @_ array is filled with the substrings.
If the delimiter patters is left off, the function splits on white space, which is defined in the regular expression /[ \t\n]+/, or spaces, tabs, and newlines.
- An optional limit argument may be passed to split(), in which case it will split into no more than LIMIT substrings.
Usage: split ([/PATTERN/], EXPRESSION, LIMIT)
Example:
@IPS = split (/\./, "127.0.0.1"); # Split on periods.
- sprintf
- Returns a string constructed according to the printf() format.
See printf() for details on how the formats are built.
Usage: sprintf (FORMAT, LIST)
Example:
$var = 4.0;
$str = "Mike";
$FullStr = sprintf ("%s worked %0.2f hours this week\n",
$str, $var);
# $FullStr = "Mike worked 4.00 hours this week\n";
- sqrt
- Returns the square root of its argument, or of $_ if no argument is supplied.
Usage: sqrt (EXPRESSION)
Example:
$num = sqrt (2);
- srand
- Sets the random seed for the pseudorandom number generator used in rand(). If the argument is omitted, time() is used.
Pseudorandom numbers are generated according to convoluted but inevitably predictable algorithms. If the seed used to start the pseudorandom numbers is known, then the pattern of numbers can be predicted. The time is imminently predictable, so its probably not a good idea to use the default argument to srand() to generate secure sequences for passwords and such. You can find many better ways to do it in the Usenet newsgroups at comp.security.unix.
Usage: srand (EXPRESSION)
Example:
srand (sqrt (time));
- stat
- Returns an array of information about a file handle, including size and modification times.
Unlike the similar C standard library functions, one of which is used to examine open files handles and the other for file names, Perls stat() is capable of doing both. Its argument can be either a file name or an open file handle.
The information returned can have different meanings for different operating systems, but generally the information that comes back takes this form, in this order:
- device Whether this is a file or device.
- inodes Number of inodes used; meaningful only on UNIX, 0 in Windows.
- mode A number indicating the permissions on the file.
- links Number of links to the file; always 1 in Windows.
- user ID UID of the files owner; always 0 in Windows.
- group ID GID of the files owner; always 0 in Windows.
- size The size of the file in bytes.
- access, modification, creation times Three fields; accurate on UNIX, but all three are the same in Windows.
- blocksize, blocks Meaningful only to BSD UNIX.
If the argument to stat() is an underline (the special file handle), the results of the last call to the function will be returned.
Usage: stat (HANDLE), stat (EXPRESSION)
Example:
($device, $inode, $mode, $link, $uid, $gid,
$size, $atime, $mtime, $ctime) = stat (FP);
- study
- Takes extra time to scan its argument. Scans $_ if no argument.
The function is called in preparation for a heavy session of pattern matches on the argument, which might considerably speed up the process. Then again, it might not. It all depends on what youre searching for and how your search patterns are constructed.
The function works by building a linked list of every character in the argument string, then it selects the rarest character and examines only those places in the string.
Usage: study (EXPRESSION)
Example:
study;
while (<>)
{
. # Input will be scanned.
.
.
}
- substr
- Takes a substring out of its argument based on an offset and optional length.
If the offset is negative, the beginning of the substring is counted backward from the end of the argument string. If the length is left off, the whole string becomes the substring.
Usage: substr (EXPRESSION, OFFSET, [LENGTH])
Example:
$str = substr ("Now is the time", 4);
# $str now = "is the time"
- symlink
- Creates a symbolic link for a file name on systems that support symbolic links. Returns 1 on success, 0 on failure with the error code in $!.
This function is not implemented in the Win32 versions of Perl.
Usage: symlink (OLDNAME, NEWNAME)
Example:
$NewName = "stuff1.wav";
symlink ("stuff.wav", $NewName)
|| die "Can't create link: $!\n";
- syscall
- Calls the internal (that is, C library) function specified as its first argument, taking any subsequent arguments to be parameters to be passed along.
It is unavailable on systems that dont implement the C syscall() function, including the Windows operating systems.
Usage: syscall (LIST)
Example:
require "syscall.ph";
syscall (&SYS_close, 1);
- sysread
- Bypasses any system buffering and other file-handling niceties to do a direct read of the handle passed to it. The arguments and functionality are identical to those for read().
The function returns the number of bytes read or 0 at EOF. The undefined value comes back on error, with the error code in $!.
Because this function sidesteps all of the standard I/O facilities, calls to read() and sysread() should not be mixed.
Usage: sysread (HANDLE, BUFFER, LENGTH, [OFFSET])
Example:
while (sysread (FP, $buf, 1)) # One char at a time.
{
$array[$n++] = $buf;
}
- system
- Used to run programs. Unlike exec(), which terminates its parent to run the specified program, system() starts the application and waits for it to finish. Your Perl script can then go on with what it was doing.
The first argument is taken to be a program file name; any subsequent arguments are passed to the program.
Perl calls wait() to determine when the external program has finished and system() returns the exit status from wait(). Divide by 256 to get the programs actual exit code.
Usage: system (LIST)
Example:
system ("notepad.exe", stuff.txt");
- syswrite
- Similar to sysread(), except this function directly writes to its handle argument. Use syswrite() instead of print() when you want to go around the standard I/O facilities, but be careful not to mix the two functions.
The optional offset argument tells the function to start writing data from somewhere other than the beginning of the buffer argument.
Returns the number of bytes actually written or the undefined value if an error occurs.
Usage: syswrite (HANDLE, BUFFER, LENGTH, [OFFSET])
Example:
foreach $val (@Array)
{
syswrite (FP, $val, length ($val));
}
- tell
- Returns the file pointer position for the handle passed to it as an argument. With no argument, tell() returns the file pointer position of the last file read.
Usage: tell (HANDLE)
Example:
$CurPos = tell (FP);
- telldir
- The directory-management analog of tell(). This function returns the current readdir() position in a directory handle obtained from opendir().
The value returned by the function is the only one that can be used with seekdir() to move to another position in the directory.
Usage: telldir (HANDLE)
Example:
$CurDirPos = telldir (DIR); # Get current position.
.
.
.
seekdir ($CurDirPos); # Move back.
- time
- Returns the number of seconds (leap seconds excluded) elapsed since midnight, January 1, 1970.
The 1970 epoch is a UNIX convention that isnt followed by all operating systems, but Perls time() works the same on all systems.
The returned value can be used with any of the Perl time functions.
Usage: time
Example:
# Print ctime()-type time.
print scalar (localtime (time)), "\n";
- times
- Fills an array of user and system CPU times for the current process and any children. (See the example below for the order of elements in the array.)
Usage: times
Example:
($user_time, $system_time, $child_user_time,
$child_system_time) = times;
- tr
- The translation operator. Used in a similar fashion to s, the substitution operator.
Optional parameters to this function are:
- c Complement; any characters in the search string are removed from the list of characters from 001 to 0377 octal and the resulting string replaces the search string.
- d Delete; removes all characters from the search string that arent in the replacement string.
- s Squeeze; if a substitution would result in more than one of the same character in the replacement list to be output, the replacement will be only one of that character.
This function is identical to the y function in sed; for that reason, tr may also be invoked with y.
Usage: tr/SEARCH/REPLACE/[c][d][s]
Example:
$NewStr =~ tr/a-z/A-Z/; # Change all to upper case.
- truncate
- Truncates the file handle or named file in its argument to the length given in the second argument.
The function gives a fatal error if it isnt implemented on your operating system. It doesnt work in the Win32 versions of Perl.
Usage: truncate (HANDLE, LEN), truncate (NAME, LEN)
Example:
truncate ("stuff.txt", 0); # Zero the file.
- umask
- Sets the UNIX umask for the current process. Returns the old one.
The umask is a UNIX permission convention that is meaningless on Windows 95 and NT. However, the function is implemented in the Win32 versions of Perl; it just has no effect and always returns 0.
Usage: umask (EXPRESSION)
Example:
umask (0666);
- undef
- Turns its argument into the undefined value or, without an argument, is itself the undefined value.
The function can be used on scalars, arrays, or &-prefixed subroutines.
Usage: undef (EXPRESSION)
Example:
if (defined ($stuff))
{
undef ($stuff);
}
- unlink
- Deletes a list of files, if possible. Returns the number of files deleted.
Usage: unlink (LIST)
Example:
@files = readdir (DIR);
$count = unlink (@files);
print "$count files were deleted\n";
- unpack
- The opposite of pack(), using the same template codes (see pack() for a detailed description of each of the codes).
This function takes a packed string and expands it into an array, based on the template passed to it.
Usage: unpack (TEMPLATE, EXPRESSION)
Example:
($name, $alias, $type, @address)
= gethostbyname ($domain);
@IP = unpack ("C4", $address[0]);
$IPAddr = join (".", @IP);
- unshift
- The opposite of shift(). Tacks a list to the front of an array, returning the number of elements in the new array.
Usage: unshift (ARRAY, LIST)
Example:
shift (@NewArray, @MoreStuff);
- utime
- Changes the access and modification times on the list of files passed to it.
This function is specific to UNIX, but it is implemented in the Win32 versions of Perl. It has no effect, however.
Usage: utime (LIST)
Example:
# Update a whole directory.
$TheTime = time;
@Files = readdir (DIR);
utime (@Files);
- values
- The partner to keys(). This function returns an array of all of the values in the associative array passed to it as an argument.
See keys() for caveats about loading large associative arrays into values(). You may want to use the iterative function each() instead.
Usage: values (ASSOCIATIVE_ARRAY)
Example:
@ValArray = values (%BigArray);
- vec
- Evaluates its string argument as an array of unsigned integers. Coupled with its BITS argument, vec() provides some of the bit- and byte-twiddling capabilities of the C language to Perl.
An OFFSET argument specifies the position of the byte you want to find. Any byte can be changed and the result is a modification of the string.
A BITS argument specifies the number of bits per element in the array; it must be one of 1, 2, 4, 8, 16, or 32. Thus, element positions are calculated by multiplying the offset by the elements per byte (BITS = 18, BITS = 24, etc.).
You can use the arithmetic bitwise operators against the results of vec().
To get a string of binary bits, use unpack() with the b* template.
Usage: vec (EXPRESSION, OFFSET, BITS)
Example:
$string = "Now is the time";
$byte = vec ($string, 8, 8); # Gets 2nd character.
- wait
- Waits for a child process to finish. The childs process ID is returned; 1 comes back if there were no children.
This function is specific to UNIX. It is not implemented in the Win32 versions of Perl.
Usage: wait
Example:
$id = wait;
if ($id < 0)
{
print "No child process\n";
}
- waitpid
- Similar to wait(), but takes as an argument a specific process ID to wait for and a number of flags indicating how the wait should be handled. See the UNIX man pages for waitpid (2) for detailed information.
This function is specific to UNIX. It is not implemented in the Win32 versions of Perl.
Usage: waitpid (PID, FLAGS)
Example:
waitpid ($ChildID, &WNOHANG);
- wantarray
- If the subroutine being executed is looking for an array value, this function returns true. See caller().
Usage: wantarray
Example:
if (wantarray)
{
return 1;
}
else
{
return undef;
}
- warn
- Identical to die() with one exception: It doesnt exit the program at the point its called.
This function prints a message to the standard output, then your Perl script continues.
Usage: warn (LIST)
Example:
open (FP, "stuff.txt")
|| warn "Warning: can't open file: $!\n";
- write
- Writes formatted records to the file passed to it as an argument.
Remember that write() is not used in normal file I/O, but only in formatted files. Normally, you will use print() to write to files.
Usage: write (HANDLE), write (EXPRESSION)
|