SEARCH
NEW RPMS
DIRECTORIES
ABOUT
FAQ
VARIOUS
BLOG

BotDetect - Real-Time Bot Detection API
 
 

MAN page from Old RedHat 5.X perl-5.004-4.i386.rpm

PERLFUNC

Section: Perl Programmers Reference Guide (1)
Updated: perl 5.004, patch 04
Index 

NAME

perlfunc - Perl builtin functions 

DESCRIPTION

The functions in this section can serve as terms in an expression.They fall into two major categories: list operators and named unaryoperators. These differ in their precedence relationship with afollowing comma. (See the precedence table in the perlop manpage.) Listoperators take more than one argument, while unary operators can nevertake more than one argument. Thus, a comma terminates the argument ofa unary operator, but merely separates the arguments of a listoperator. A unary operator generally provides a scalar context to itsargument, while a list operator may provide either scalar and listcontexts for its arguments. If it does both, the scalar arguments willbe first, and the list argument will follow. (Note that there can everbe only one list argument.) For instance, splice() has three scalararguments followed by a list.

In the syntax descriptions that follow, list operators that expect alist (and provide list context for the elements of the list) are shownwith LIST as an argument. Such a list may consist of any combinationof scalar arguments or list values; the list values will be includedin the list as if each individual element were interpolated at thatpoint in the list, forming a longer single-dimensional list value.Elements of the LIST should be separated by commas.

Any function in the list below may be used either with or withoutparentheses around its arguments. (The syntax descriptions omit theparentheses.) If you use the parentheses, the simple (but occasionallysurprising) rule is this: It LOOKS like a function, therefore it IS afunction, and precedence doesn't matter. Otherwise it's a listoperator or unary operator, and precedence does matter. And whitespacebetween the function and left parenthesis doesn't count---so you need tobe careful sometimes:

    print 1+2+4;        # Prints 7.    print(1+2) + 4;     # Prints 3.    print (1+2)+4;      # Also prints 3!    print +(1+2)+4;     # Prints 7.    print ((1+2)+4);    # Prints 7.
If you run Perl with the -w switch it can warn you about this. Forexample, the third line above produces:

    print (...) interpreted as function at - line 1.    Useless use of integer addition in void context at - line 1.
For functions that can be used in either a scalar or list context,nonabortive failure is generally indicated in a scalar context byreturning the undefined value, and in a list context by returning thenull list.

Remember the following rule:

THERE IS NO GENERAL RULE FOR CONVERTING A LIST INTO A SCALAR!

Each operator and function decides which sort of value it would be mostappropriate to return in a scalar context. Some operators return thelength of the list that would have been returned in a list context. Someoperators return the first value in the list. Some operators return thelast value in the list. Some operators return a count of successfuloperations. In general, they do what you want, unless you wantconsistency. 

Perl Functions by Category

Here are Perl's functions (including things that look likefunctions, like some of the keywords and named operators)arranged by category. Some functions appear in morethan one place.
Functions for SCALA
chomp, chop, chr, crypt, hex, index, lc, lcfirst, length,oct, ord, pack, q/STRING/, qq/STRING/, reverse, rindex,sprintf, substr, tr///, uc, ucfirst, y///
Regular expressions and pattern matching
m//, pos, quotemeta, s///, split, study
Numeric functions
abs, atan2, cos, exp, hex, int, log, oct, rand, sin, sqrt,srand
Functions for real @ARRAYs
pop, push, shift, splice, unshift
Functions for list data
grep, join, map, qw/STRING/, reverse, sort, unpack
Functions for real %HASHes
delete, each, exists, keys, values
Input and output functions
binmode, close, closedir, dbmclose, dbmopen, die, eof,fileno, flock, format, getc, print, printf, read, readdir,rewinddir, seek, seekdir, select, syscall, sysread, sysseek,syswrite, tell, telldir, truncate, warn, write
Functions for fixed length data or records
pack, read, syscall, sysread, syswrite, unpack, vec
Functions for filehandles, files, or directories
-X, chdir, chmod, chown, chroot, fcntl, glob, ioctl, link,lstat, mkdir, open, opendir, readlink, rename, rmdir,stat, symlink, umask, unlink, utime
Keywords related to the control flow of your perl program
caller, continue, die, do, dump, eval, exit, goto, last,next, redo, return, sub, wantarray
Keywords related to scoping
caller, import, local, my, package, use
Miscellaneous functions
defined, dump, eval, formline, local, my, reset, scalar,undef, wantarray
Functions for processes and process groups
alarm, exec, fork, getpgrp, getppid, getpriority, kill,pipe, qx/STRING/, setpgrp, setpriority, sleep, system,times, wait, waitpid
Keywords related to perl modules
do, import, no, package, require, use
Keywords related to classes and object-orientedness
bless, dbmclose, dbmopen, package, ref, tie, tied, untie, use
Low-level socket functions
accept, bind, connect, getpeername, getsockname,getsockopt, listen, recv, send, setsockopt, shutdown,socket, socketpair
System V interprocess communication functions
msgctl, msgget, msgrcv, msgsnd, semctl, semget, semop,shmctl, shmget, shmread, shmwrite
Fetching user and group info
endgrent, endhostent, endnetent, endpwent, getgrent,getgrgid, getgrnam, getlogin, getpwent, getpwnam,getpwuid, setgrent, setpwent
Fetching network info
endprotoent, endservent, gethostbyaddr, gethostbyname,gethostent, getnetbyaddr, getnetbyname, getnetent,getprotobyname, getprotobynumber, getprotoent,getservbyname, getservbyport, getservent, sethostent,setnetent, setprotoent, setservent
Time-related functions
gmtime, localtime, time, times
Functions new in perl5
abs, bless, chomp, chr, exists, formline, glob, import, lc,lcfirst, map, my, no, prototype, qx, qw, readline, readpipe,ref, sub*, sysopen, tie, tied, uc, ucfirst, untie, use

* - sub was a keyword in perl4, but in perl5 it is anoperator which can be used in expressions.

Functions obsoleted in perl5
dbmclose, dbmopen
 

Alphabetical Listing of Perl Functions


-X FILEHANDLE

-X EXPR

-X
A file test, where X is one of the letters listed below. This unaryoperator takes one argument, either a filename or a filehandle, andtests the associated file to see if something is true about it. If theargument is omitted, tests $_, except for -t, which tests STDIN.Unless otherwise documented, it returns 1 for TRUE and '' for FALSE, orthe undefined value if the file doesn't exist. Despite the funnynames, precedence is the same as any other named unary operator, andthe argument may be parenthesized like any other unary operator. Theoperator may be any of:

    -r  File is readable by effective uid/gid.    -w  File is writable by effective uid/gid.    -x  File is executable by effective uid/gid.    -o  File is owned by effective uid.
    -R  File is readable by real uid/gid.    -W  File is writable by real uid/gid.    -X  File is executable by real uid/gid.    -O  File is owned by real uid.
    -e  File exists.    -z  File has zero size.    -s  File has nonzero size (returns size).
    -f  File is a plain file.    -d  File is a directory.    -l  File is a symbolic link.    -p  File is a named pipe (FIFO).    -S  File is a socket.    -b  File is a block special file.    -c  File is a character special file.    -t  Filehandle is opened to a tty.
    -u  File has setuid bit set.    -g  File has setgid bit set.    -k  File has sticky bit set.
    -T  File is a text file.    -B  File is a binary file (opposite of -T).
    -M  Age of file in days when script started.    -A  Same for access time.    -C  Same for inode change time.
The interpretation of the file permission operators -r, -R, -w,-W, -x, and -X is based solely on the mode of the file and theuids and gids of the user. There may be other reasons you can't actuallyread, write or execute the file. Also note that, for the superuser,-r, -R, -w, and -W always return 1, and -x and -X return1 if any execute bit is set in the mode. Scripts run by the superuser maythus need to do a stat() to determine the actual mode of thefile, or temporarily set the uid to something else.

Example:

    while (<>) {        chop;        next unless -f $_;      # ignore specials        ...    }
Note that -s/a/b/ does not do a negated substitution. Saying-exp($foo) still works as expected, however---only single lettersfollowing a minus are interpreted as file tests.

The -T and -B switches work as follows. The first block or so of thefile is examined for odd characters such as strange control codes orcharacters with the high bit set. If too many odd characters (>30%)are found, it's a -B file, otherwise it's a -T file. Also, any filecontaining null in the first block is considered a binary file. If -Tor -B is used on a filehandle, the current stdio buffer is examinedrather than the first block. Both -T and -B return TRUE on a nullfile, or a file at EOF when testing a filehandle. Because you have toread a file to do the -T test, on most occasions you want to use a -fagainst the file first, as in next unless -f $file && -T $file.

If any of the file tests (or either the stat() or lstat() operators) are giventhe special filehandle consisting of a solitary underline, then the statstructure of the previous file test (or stat operator) is used, savinga system call. (This doesn't work with -t, and you need to rememberthat lstat() and -l will leave values in the stat structure for thesymbolic link, not the real file.) Example:

    print "Can do.\n" if -r $a || -w _ || -x _;
    stat($filename);    print "Readable\n" if -r _;    print "Writable\n" if -w _;    print "Executable\n" if -x _;    print "Setuid\n" if -u _;    print "Setgid\n" if -g _;    print "Sticky\n" if -k _;    print "Text\n" if -T _;    print "Binary\n" if -B _;

abs VALUE

abs
Returns the absolute value of its argument.If VALUE is omitted, uses $_.
accept NEWSOCKET,GENERICSOCKET
Accepts an incoming socket connect, just as the accept(2) system calldoes. Returns the packed address if it succeeded, FALSE otherwise.See example in the section on Sockets: Client/Server Communication in the perlipc manpage.
alarm SECONDS

alarm
Arranges to have a SIGALRM delivered to this process after thespecified number of seconds have elapsed. If SECONDS is not specified,the value stored in $_ is used. (On some machines,unfortunately, the elapsed time may be up to one second less than youspecified because of how seconds are counted.) Only one timer may becounting at once. Each call disables the previous timer, and anargument of 0 may be supplied to cancel the previous timer withoutstarting a new one. The returned value is the amount of time remainingon the previous timer.

For delays of finer granularity than one second, you may use Perl'ssyscall() interface to access setitimer(2) if your system supports it,or else see the select() entry elsewhere in this document . It is usually a mistake to intermix alarm()and sleep() calls.

If you want to use alarm() to time out a system call you need to use aneval/die pair. You can't rely on the alarm causing the system call tofail with $! set to EINTR because Perl sets up signal handlers torestart system calls on some systems. Using eval/die always works.

    eval {        local $SIG{ALRM} = sub { die "alarm\n" };       # NB \n required        alarm $timeout;        $nread = sysread SOCKET, $buffer, $size;        alarm 0;    };    die if $@ && $@ ne "alarm\n";       # propagate errors    if ($@) {        # timed out    }    else {        # didn't    }

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

For the tangent operation, you may use the POSIX::tan()function, or use the familiar relation:

    sub tan { sin($_[0]) / cos($_[0])  }

bind SOCKET,NAME
Binds a network address to a socket, just as the bind system calldoes. Returns TRUE if it succeeded, FALSE otherwise. NAME should be apacked address of the appropriate type for the socket. See the examples inthe section on Sockets: Client/Server Communication in the perlipc manpage.
binmode FILEHANDLE
Arranges for the file to be read or written in ``binary'' mode in operatingsystems that distinguish between binary and text files. Files that arenot in binary mode have CR LF sequences translated to LF on input and LFtranslated to CR LF on output. Binmode has no effect under Unix; in MS-DOSand similarly archaic systems, it may be imperative---otherwise yourMS-DOS-damaged C library may mangle your file. The key distinction betweensystems that need binmode and those that don't is their text fileformats. Systems like Unix and Plan9 that delimit lines with a singlecharacter, and that encode that character in C as `\n', do not needbinmode. The rest need it. If FILEHANDLE is an expression, the valueis taken as the name of the filehandle.
bless REF,CLASSNAME

bless REF
This function tells the thingy referenced by REF that it is nowan object in the CLASSNAME package---or the current package if no CLASSNAMEis specified, which is often the case. It returns the reference forconvenience, because a bless() is often the last thing in a constructor.Always use the two-argument version if the function doing the blessingmight be inherited by a derived class. See the perlobj manpage for more about theblessing (and blessings) of objects.
caller EXPR

caller
Returns the context of the current subroutine call. In a scalar context,returns the caller's package name if there is a caller, that is, ifwe're in a subroutine or eval() or require(), and the undefined valueotherwise. In a list context, returns

    ($package, $filename, $line) = caller;
With EXPR, it returns some extra information that the debugger uses toprint a stack trace. The value of EXPR indicates how many call framesto go back before the current one.

    ($package, $filename, $line, $subroutine,     $hasargs, $wantarray, $evaltext, $is_require) = caller($i);
Here $subroutine may be "(eval)" if the frame is not a subroutinecall, but an eval. In such a case additional elements $evaltext and$is_require are set: $is_require is true if the frame is created by arequire or use statement, $evaltext contains the text of theeval EXPR statement. In particular, for a eval BLOCK statement,$filename is "(eval)", but $evaltext is undefined. (Note also thateach use statement creates a require frame inside an eval EXPR)frame.

Furthermore, when called from within the DB package, caller returns moredetailed information: it sets the list variable @DB::args to be thearguments with which the subroutine was invoked.

chdir EXPR
Changes the working directory to EXPR, if possible. If EXPR isomitted, changes to home directory. Returns TRUE upon success, FALSEotherwise. See example under die().
chmod LIST
Changes the permissions of a list of files. The first element of thelist must be the numerical mode, which should probably be an octalnumber, and which definitely should not a string of octal digits:0644 is okay, '0644' is not. Returns the number of filessuccessfully changed. See also the oct entry elsewhere in this document if all you have is a string.

    $cnt = chmod 0755, 'foo', 'bar';    chmod 0755, @executables;    $mode = '0644'; chmod $mode, 'foo';      # !!! sets mode to --w----r-T    $mode = '0644'; chmod oct($mode), 'foo'; # this is better    $mode = 0644;   chmod $mode, 'foo';      # this is best

chomp VARIABLE

chomp LIST

chomp
This is a slightly safer version of the chop entry elsewhere in this document . It removes anyline ending that corresponds to the current value of $/ (also known as$INPUT_RECORD_SEPARATOR in the English module). It returns the totalnumber of characters removed from all its arguments. It's often used toremove the newline from the end of an input record when you're worriedthat the final record may be missing its newline. When in paragraph mode($/ = ""), it removes all trailing newlines from the string. IfVARIABLE is omitted, it chomps $_. Example:

    while (<>) {        chomp;  # avoid \n on last field        @array = split(/:/);        ...    }
You can actually chomp anything that's an lvalue, including an assignment:

    chomp($cwd = `pwd`);    chomp($answer = <STDIN>);
If you chomp a list, each element is chomped, and the total number ofcharacters removed is returned.
chop VARIABLE

chop LIST

chop
Chops off the last character of a string and returns the characterchopped. It's used primarily to remove the newline from the end of aninput record, but is much more efficient than s/\n// because it neitherscans nor copies the string. If VARIABLE is omitted, chops $_.Example:

    while (<>) {        chop;   # avoid \n on last field        @array = split(/:/);        ...    }
You can actually chop anything that's an lvalue, including an assignment:

    chop($cwd = `pwd`);    chop($answer = <STDIN>);
If you chop a list, each element is chopped. Only the value of thelast chop is returned.

Note that chop returns the last character. To return all but the lastcharacter, use substr($string, 0, -1).

chown LIST
Changes the owner (and group) of a list of files. The first twoelements of the list must be the NUMERICAL uid and gid, in that order.Returns the number of files successfully changed.

    $cnt = chown $uid, $gid, 'foo', 'bar';    chown $uid, $gid, @filenames;
Here's an example that looks up nonnumeric uids in the passwd file:

    print "User: ";    chop($user = <STDIN>);    print "Files: "    chop($pattern = <STDIN>);
    ($login,$pass,$uid,$gid) = getpwnam($user)        or die "$user not in passwd file";
    @ary = <${pattern}>;        # expand filenames    chown $uid, $gid, @ary;
On most systems, you are not allowed to change the ownership of thefile unless you're the superuser, although you should be able to changethe group to any of your secondary groups. On insecure systems, theserestrictions may be relaxed, but this is not a portable assumption.
chr NUMBER

chr
Returns the character represented by that NUMBER in the character set.For example, chr(65) is ``A'' in ASCII. For the reverse, use the ord entry elsewhere in this document .

If NUMBER is omitted, uses $_.

chroot FILENAME

chroot
This function works as the system call by the same name: it makes thenamed directory the new root directory for all further pathnames thatbegin with a ``/'' by your process and all of its children. (It doesn'tchange your current working directory, which is unaffected.) For securityreasons, this call is restricted to the superuser. If FILENAME isomitted, does chroot to $_.
close FILEHANDLE
Closes the file or pipe associated with the file handle, returning TRUEonly if stdio successfully flushes buffers and closes the system filedescriptor.

You don't have to close FILEHANDLE if you are immediately going to doanother open() on it, because open() will close it for you. (Seeopen().) However, an explicit close on an input file resets the linecounter ($.), while the implicit close done by open() does not.

If the file handle came from a piped open close will additionallyreturn FALSE if one of the other system calls involved fails or if theprogram exits with non-zero status. (If the only problem was that theprogram exited non-zero $! will be set to 0.) Also, closing a pipe willwait for the process executing on the pipe to complete, in case youwant to look at the output of the pipe afterwards. Closing a pipeexplicitly also puts the exit status value of the command into $?.Example:

    open(OUTPUT, '|sort >foo')  # pipe to sort        or die "Can't start sort: $!";    ...                         # print stuff to output    close OUTPUT                # wait for sort to finish        or warn $! ? "Error closing sort pipe: $!"                   : "Exit status $? from sort";    open(INPUT, 'foo')          # get sort's results        or die "Can't open 'foo' for input: $!";
FILEHANDLE may be an expression whose value gives the real filehandle name.
closedir DIRHANDLE
Closes a directory opened by opendir().
connect SOCKET,NAME
Attempts to connect to a remote socket, just as the connect system calldoes. Returns TRUE if it succeeded, FALSE otherwise. NAME should be apacked address of the appropriate type for the socket. See the examples inthe section on Sockets: Client/Server Communication in the perlipc manpage.
continue BLOCK
Actually a flow control statement rather than a function. If there is acontinue BLOCK attached to a BLOCK (typically in a while orforeach), it is always executed just before the conditional is about tobe evaluated again, just like the third part of a for loop in C. Thusit can be used to increment a loop variable, even when the loop has beencontinued via the next statement (which is similar to the C continuestatement).
cos EXPR
Returns the cosine of EXPR (expressed in radians). If EXPR is omittedtakes cosine of $_.

For the inverse cosine operation, you may use the POSIX::acos()function, or use this relation:

    sub acos { atan2( sqrt(1 - $_[0] * $_[0]), $_[0] ) }

crypt PLAINTEXT,SALT
Encrypts a string exactly like the crypt(3) function in the C library(assuming that you actually have a version there that has not beenextirpated as a potential munition). This can prove useful for checkingthe password file for lousy passwords, amongst other things. Only theguys wearing white hats should do this.

Note that crypt is intended to be a one-way function, much like breakingeggs to make an omelette. There is no (known) corresponding decryptfunction. As a result, this function isn't all that useful forcryptography. (For that, see your nearby CPAN mirror.)

Here's an example that makes sure that whoever runs this program knowstheir own password:

    $pwd = (getpwuid($<))[1];    $salt = substr($pwd, 0, 2);
    system "stty -echo";    print "Password: ";    chop($word = <STDIN>);    print "\n";    system "stty echo";
    if (crypt($word, $salt) ne $pwd) {        die "Sorry...\n";    } else {        print "ok\n";    }
Of course, typing in your own password to whoever asks youfor it is unwise.
dbmclose HASH
[This function has been superseded by the untie() function.]

Breaks the binding between a DBM file and a hash.

dbmopen HASH,DBNAME,MODE
[This function has been superseded by the tie() function.]

This binds a dbm(3), ndbm(3), sdbm(3), gdbm(), or Berkeley DB file to ahash. HASH is the name of the hash. (Unlike normal open, the firstargument is NOT a filehandle, even though it looks like one). DBNAMEis the name of the database (without the .dir or .pag extension ifany). If the database does not exist, it is created with protectionspecified by MODE (as modified by the umask()). If your system supportsonly the older DBM functions, you may perform only one dbmopen() in yourprogram. In older versions of Perl, if your system had neither DBM norndbm, calling dbmopen() produced a fatal error; it now falls back tosdbm(3).

If you don't have write access to the DBM file, you can only read hashvariables, not set them. If you want to test whether you can write,either use file tests or try setting a dummy hash entry inside an eval(),which will trap the error.

Note that functions such as keys() and values() may return huge arrayvalues when used on large DBM files. You may prefer to use the each()function to iterate over large DBM files. Example:

    # print out history file offsets    dbmopen(%HIST,'/usr/lib/news/history',0666);    while (($key,$val) = each %HIST) {        print $key, ' = ', unpack('L',$val), "\n";    }    dbmclose(%HIST);
See also the AnyDBM_File manpage for a more general description of the pros andcons of the various dbm approaches, as well as the DB_File manpage for a particularlyrich implementation.
defined EXPR

defined
Returns a Boolean value telling whether EXPR has a value other thanthe undefined value undef. If EXPR is not present, $_ will bechecked.

Many operations return undef to indicate failure, end of file,system error, uninitialized variable, and other exceptionalconditions. This function allows you to distinguish undef fromother values. (A simple Boolean test will not distinguish amongundef, zero, the empty string, and ``0'', which are all equallyfalse.) Note that since undef is a valid scalar, its presencedoesn't necessarily indicate an exceptional condition: pop()returns undef when its argument is an empty array, or when theelement to return happens to be undef.

You may also use defined() to check whether a subroutine exists. Onthe other hand, use of defined() upon aggregates (hashes and arrays)is not guaranteed to produce intuitive results, and should probably beavoided.

When used on a hash element, it tells you whether the value is defined,not whether the key exists in the hash. Use the exists entry elsewhere in this document for the latterpurpose.

Examples:

    print if defined $switch{'D'};    print "$val\n" while defined($val = pop(@ary));    die "Can't readlink $sym: $!"        unless defined($value = readlink $sym);    sub foo { defined &$bar ? &$bar(@_) : die "No bar"; }    $debugging = 0 unless defined $debugging;
Note: Many folks tend to overuse defined(), and then are surprised todiscover that the number 0 and "" (the zero-length string) are, in fact,defined values. For example, if you say

    "ab" =~ /a(.*)b/;
the pattern match succeeds, and $1 is defined, despite the fact that itmatched "nothing". But it didn't really match nothing---rather, itmatched something that happened to be 0 characters long. This is allvery above-board and honest. When a function returns an undefined value,it's an admission that it couldn't give you an honest answer. So youshould use defined() only when you're questioning the integrity of whatyou're trying to do. At other times, a simple comparison to 0 or "" iswhat you want.

Currently, using defined() on an entire array or hash reports whethermemory for that aggregate has ever been allocated. So an array you setto the empty list appears undefined initially, and one that once was fulland that you then set to the empty list still appears defined. Youshould instead use a simple test for size:

    if (@an_array) { print "has array elements\n" }    if (%a_hash)   { print "has hash members\n"   }
Using undef() on these, however, does clear their memory and then reportthem as not defined anymore, but you shoudln't do that unless you don'tplan to use them again, because it saves time when you load them upagain to have memory already ready to be filled.

This counterintuitive behaviour of defined() on aggregates may bechanged, fixed, or broken in a future release of Perl.

See also the undef, exists, and ref entries elsewhere in this document .

delete EXPR
Deletes the specified key(s) and their associated values from a hash.For each key, returns the deleted value associated with that key, orthe undefined value if there was no such key. Deleting from $ENV{}modifies the environment. Deleting from a hash tied to a DBM filedeletes the entry from the DBM file. (But deleting from a tie()d hashdoesn't necessarily return anything.)

The following deletes all the values of a hash:

    foreach $key (keys %HASH) {        delete $HASH{$key};    }
And so does this:

    delete @HASH{keys %HASH}
(But both of these are slower than the undef() command.) Note that theEXPR can be arbitrarily complicated as long as the final operation is ahash element lookup or hash slice:

    delete $ref->[$x][$y]{$key};    delete @{$ref->[$x][$y]}{$key1, $key2, @morekeys};

die LIST
Outside of an eval(), prints the value of LIST to STDERR and exits withthe current value of $! (errno). If $! is 0, exits with the value of($? >> 8) (backtick `command` status). If ($? >> 8)is 0, exits with 255. Inside an eval(), the error message is stuffed into$@, and the eval() is terminated with the undefined value; this makesdie() the way to raise an exception.

Equivalent examples:

    die "Can't cd to spool: $!\n" unless chdir '/usr/spool/news';    chdir '/usr/spool/news' or die "Can't cd to spool: $!\n"
If the value of EXPR does not end in a newline, the current script linenumber and input line number (if any) are also printed, and a newlineis supplied. Hint: sometimes appending ``, stopped'' to your messagewill cause it to make better sense when the string ``at foo line 123'' isappended. Suppose you are running script ``canasta''.

    die "/etc/games is no good";    die "/etc/games is no good, stopped";
produce, respectively

    /etc/games is no good at canasta line 123.    /etc/games is no good, stopped at canasta line 123.
See also exit() and warn().

If LIST is empty and $@ already contains a value (typically from aprevious eval) that value is reused after appending ``\t...propagated''.This is useful for propagating exceptions:

    eval { ... };    die unless $@ =~ /Expected exception/;
If $@ is empty then the string ``Died'' is used.

You can arrange for a callback to be called just before the die() doesits deed, by setting the $SIG{__DIE__} hook. The associated handlerwill be called with the error text and can change the error message, ifit sees fit, by calling die() again. See the section on $SIG{expr} in the perlvar manpage for details onsetting %SIG entries, and the section on eval BLOCK for some examples.

Note that the $SIG{__DIE__} hook is called even inside eval()edblocks/strings. If one wants the hook to do nothing in suchsituations, put

        die @_ if $^S;
as the first line of the handler (see the section on $^S in the perlvar manpage).
do BLOCK
Not really a function. Returns the value of the last command in thesequence of commands indicated by BLOCK. When modified by a loopmodifier, executes the BLOCK once before testing the loop condition.(On other statements the loop modifiers test the conditional first.)
do SUBROUTINE(LIST)
A deprecated form of subroutine call. See the perlsub manpage.
do EXPR
Uses the value of EXPR as a filename and executes the contents of thefile as a Perl script. Its primary use is to include subroutinesfrom a Perl subroutine library.

    do 'stat.pl';
is just like

    scalar eval `cat stat.pl`;
except that it's more efficient, more concise, keeps track of thecurrent filename for error messages, and searches all the -Ilibraries if the file isn't in the current directory (see also the @INCarray in the section on Predefined Names in the perlvar manpage). It's the same, however, in that it doesreparse the file every time you call it, so you probably don't want todo this inside a loop.

Note that inclusion of library modules is better done with theuse() and require() operators, which also do error checkingand raise an exception if there's a problem.

dump LABEL
This causes an immediate core dump. Primarily this is so that you canuse the undump program to turn your core dump into an executable binaryafter having initialized all your variables at the beginning of theprogram. When the new binary is executed it will begin by executing agoto LABEL (with all the restrictions that goto suffers). Think ofit as a goto with an intervening core dump and reincarnation. If LABELis omitted, restarts the program from the top. WARNING: any filesopened at the time of the dump will NOT be open any more when theprogram is reincarnated, with possible resulting confusion on the partof Perl. See also -u option in the perlrun manpage.

Example:

    #!/usr/bin/perl    require 'getopt.pl';    require 'stat.pl';    %days = (        'Sun' => 1,        'Mon' => 2,        'Tue' => 3,        'Wed' => 4,        'Thu' => 5,        'Fri' => 6,        'Sat' => 7,    );
    dump QUICKSTART if $ARGV[0] eq '-d';
    QUICKSTART:    Getopt('f');

each HASH
When called in a list context, returns a 2-element array consisting of thekey and value for the next element of a hash, so that you can iterate overit. When called in a scalar context, returns the key for only the nextelement in the hash. (Note: Keys may be "0" or "", which are logicallyfalse; you may wish to avoid constructs like while ($k = each %foo) {}for this reason.)

Entries are returned in an apparently random order. When the hash isentirely read, a null array is returned in list context (which whenassigned produces a FALSE (0) value), and undef is returned in ascalar context. The next call to each() after that will start iteratingagain. There is a single iterator for each hash, shared by all each(),keys(), and values() function calls in the program; it can be reset byreading all the elements from the hash, or by evaluating keys HASH orvalues HASH. If you add or delete elements of a hash while you'reiterating over it, you may get entries skipped or duplicated, so don't.

The following prints out your environment like the printenv(1) program,only in a different order:

    while (($key,$value) = each %ENV) {        print "$key=$value\n";    }
See also keys() and values().
eof FILEHANDLE

eof ()

eof
Returns 1 if the next read on FILEHANDLE will return end of file, or ifFILEHANDLE is not open. FILEHANDLE may be an expression whose valuegives the real filehandle name. (Note that this function actuallyreads a character and then ungetc()s it, so it is not very useful in aninteractive context.) Do not read from a terminal file (or calleof(FILEHANDLE) on it) after end-of-file is reached. Filetypes suchas terminals may lose the end-of-file condition if you do.

An eof without an argument uses the last file read as argument.Empty parentheses () may be used to indicate the pseudo file formed ofthe files listed on the command line, i.e., eof() is reasonable touse inside a while (<>) loop to detect the end of only thelast file. Use eof(ARGV) or eof without the parentheses to testEACH file in a while (<>) loop. Examples:

    # reset line numbering on each input file    while (<>) {        print "$.\t$_";        close(ARGV) if (eof);   # Not eof().    }
    # insert dashes just before last line of last file    while (<>) {        if (eof()) {            print "--------------\n";            close(ARGV);        # close or break; is needed if we                                # are reading from the terminal        }        print;    }
Practical hint: you almost never need to use eof in Perl, because theinput operators return undef when they run out of data.
eval EXPR

eval BLOCK
EXPR is parsed and executed as if it were a little Perl program. Itis executed in the context of the current Perl program, so that anyvariable settings or subroutine and format definitions remain afterwards.The value returned is the value of the last expression evaluated, or areturn statement may be used, just as with subroutines. The lastexpression is evaluated in scalar or array context, depending on thecontext of the eval.

If there is a syntax error or runtime error, or a die() statement isexecuted, an undefined value is returned by eval(), and $@ is set to theerror message. If there was no error, $@ is guaranteed to be a nullstring. If EXPR is omitted, evaluates $_. The final semicolon, ifany, may be omitted from the expression. Beware that using eval()neither silences perl from printing warnings to STDERR, nor does itstuff the text of warning messages into $@. To do either of those,you have to use the $SIG{__WARN__} facility. See warn() and the perlvar manpage.

Note that, because eval() traps otherwise-fatal errors, it is useful fordetermining whether a particular feature (such as socket() or symlink())is implemented. It is also Perl's exception trapping mechanism, wherethe die operator is used to raise exceptions.

If the code to be executed doesn't vary, you may use the eval-BLOCKform to trap run-time errors without incurring the penalty ofrecompiling each time. The error, if any, is still returned in $@.Examples:

    # make divide-by-zero nonfatal    eval { $answer = $a / $b; }; warn $@ if $@;
    # same thing, but less efficient    eval '$answer = $a / $b'; warn $@ if $@;
    # a compile-time error    eval { $answer = };
    # a run-time error    eval '$answer =';   # sets $@
When using the eval{} form as an exception trap in libraries, you maywish not to trigger any __DIE__ hooks that user code may haveinstalled. You can use the local $SIG{__DIE__} construct for thispurpose, as shown in this example:

    # a very private exception trap for divide-by-zero    eval { local $SIG{'__DIE__'}; $answer = $a / $b; }; warn $@ if $@;
This is especially significant, given that __DIE__ hooks can calldie() again, which has the effect of changing their error messages:

    # __DIE__ hooks may modify error messages    {       local $SIG{'__DIE__'} = sub { (my $x = $_[0]) =~ s/foo/bar/g; die $x };       eval { die "foo foofs here" };       print $@ if $@;                # prints "bar barfs here"    }
With an eval(), you should be especially careful to remember what'sbeing looked at when:

    eval $x;            # CASE 1    eval "$x";          # CASE 2
    eval '$x';          # CASE 3    eval { $x };        # CASE 4
    eval "\$$x++"       # CASE 5    $$x++;              # CASE 6
Cases 1 and 2 above behave identically: they run the code contained inthe variable $x. (Although case 2 has misleading double quotes makingthe reader wonder what else might be happening (nothing is).) Cases 3and 4 likewise behave in the same way: they run the code `$x', whichdoes nothing but return the value of $x. (Case 4 is preferred forpurely visual reasons, but it also has the advantage of compiling atcompile-time instead of at run-time.) Case 5 is a place wherenormally you WOULD like to use double quotes, except that in thisparticular situation, you can just use symbolic references instead, asin case 6.
exec LIST
The exec() function executes a system command AND NEVER RETURNS -use system() instead of exec() if you want it to return. It fails andreturns FALSE only if the command does not exist and it is executeddirectly instead of via your system's command shell (see below).

If there is more than one argument in LIST, or if LIST is an array withmore than one value, calls execvp(3) with the arguments in LIST. Ifthere is only one scalar argument, the argument is checked for shellmetacharacters, and if there are any, the entire argument is passed tothe system's command shell for parsing (this is /bin/sh -c on Unixplatforms, but varies on other platforms). If there are no shellmetacharacters in the argument, it is split into words and passeddirectly to execvp(), which is more efficient. Note: exec() andsystem() do not flush your output buffer, so you may need to set $|to avoid lost output. Examples:

    exec '/bin/echo', 'Your arguments are: ', @ARGV;    exec "sort $outfile | uniq";
If you don't really want to execute the first argument, but want to lieto the program you are executing about its own name, you can specifythe program you actually want to run as an ``indirect object'' (without acomma) in front of the LIST. (This always forces interpretation of theLIST as a multivalued list, even if there is only a single scalar inthe list.) Example:

    $shell = '/bin/csh';    exec $shell '-sh';          # pretend it's a login shell
or, more directly,

    exec {'/bin/csh'} '-sh';    # pretend it's a login shell
When the arguments get executed via the system shell, results willbe subject to its quirks and capabilities. See the section on `STRING` in the perlop manpagefor details.
exists EXPR
Returns TRUE if the specified hash key exists in its hash array, evenif the corresponding value is undefined.

    print "Exists\n" if exists $array{$key};    print "Defined\n" if defined $array{$key};    print "True\n" if $array{$key};
A hash element can be TRUE only if it's defined, and defined ifit exists, but the reverse doesn't necessarily hold true.

Note that the EXPR can be arbitrarily complicated as long as the finaloperation is a hash key lookup:

    if (exists $ref->[$x][$y]{$key}) { ... }

exit EXPR
Evaluates EXPR and exits immediately with that value. (Actually, itcalls any defined END routines first, but the END routines may notabort the exit. Likewise any object destructors that need to be calledare called before exit.) Example:

    $ans = <STDIN>;    exit 0 if $ans =~ /^[Xx]/;
See also die(). If EXPR is omitted, exits with 0 status. The onlyuniversally portable values for EXPR are 0 for success and 1 for error;all other values are subject to unpredictable interpretation dependingon the environment in which the Perl program is running.

You shouldn't use exit() to abort a subroutine if there's any chance thatsomeone might want to trap whatever error happened. Use die() instead,which can be trapped by an eval().

exp EXPR

exp
Returns e (the natural logarithm base) to the power of EXPR.If EXPR is omitted, gives exp($_).
fcntl FILEHANDLE,FUNCTION,SCALAR
Implements the fcntl(2) function. You'll probably have to say

    use Fcntl;
first to get the correct function definitions. Argument processing andvalue return works just like ioctl() below. Note that fcntl() will producea fatal error if used on a machine that doesn't implement fcntl(2).For example:

    use Fcntl;    fcntl($filehandle, F_GETLK, $packed_return_buffer);

fileno FILEHANDLE
Returns the file descriptor for a filehandle. This is useful forconstructing bitmaps for select(). If FILEHANDLE is an expression, thevalue is taken as the name of the filehandle.
flock FILEHANDLE,OPERATION
Calls flock(2), or an emulation of it, on FILEHANDLE. Returns TRUE forsuccess, FALSE on failure. Produces a fatal error if used on a machinethat doesn't implement flock(2), fcntl(2) locking, or lockf(3). flock()is Perl's portable file locking interface, although it locks only entirefiles, not records.

OPERATION is one of LOCK_SH, LOCK_EX, or LOCK_UN, possibly combined withLOCK_NB. These constants are traditionally valued 1, 2, 8 and 4, butyou can use the symbolic names if import them from the Fcntl module,either individually, or as a group using the `:flock' tag. LOCK_SHrequests a shared lock, LOCK_EX requests an exclusive lock, and LOCK_UNreleases a previously requested lock. If LOCK_NB is added to LOCK_SH orLOCK_EX then flock() will return immediately rather than blockingwaiting for the lock (check the return status to see if you got it).

To avoid the possibility of mis-coordination, Perl flushes FILEHANDLEbefore (un)locking it.

Note that the emulation built with lockf(3) doesn't provide sharedlocks, and it requires that FILEHANDLE be open with write intent. Theseare the semantics that lockf(3) implements. Most (all?) systemsimplement lockf(3) in terms of fcntl(2) locking, though, so thediffering semantics shouldn't bite too many people.

Note also that some versions of flock() cannot lock things over thenetwork; you would need to use the more system-specific fcntl() forthat. If you like you can force Perl to ignore your system's flock(2)function, and so provide its own fcntl(2)-based emulation, by passingthe switch -Ud_flock to the Configure program when you configureperl.

Here's a mailbox appender for BSD systems.

    use Fcntl ':flock'; # import LOCK_* constants
    sub lock {        flock(MBOX,LOCK_EX);        # and, in case someone appended        # while we were waiting...        seek(MBOX, 0, 2);    }
    sub unlock {        flock(MBOX,LOCK_UN);    }
    open(MBOX, ">>/usr/spool/mail/$ENV{'USER'}")            or die "Can't open mailbox: $!";
    lock();    print MBOX $msg,"\n\n";    unlock();
See also the DB_File manpage for other flock() examples.
fork
Does a fork(2) system call. Returns the child pid to the parent processand 0 to the child process, or undef if the fork is unsuccessful.Note: unflushed buffers remain unflushed in both processes, which meansyou may need to set $| ($AUTOFLUSH in English) or call the autoflush()method of IO::Handle to avoid duplicate output.

If you fork() without ever waiting on your children, you will accumulatezombies:

    $SIG{CHLD} = sub { wait };
There's also the double-fork trick (error checking onfork() returns omitted);

    unless ($pid = fork) {        unless (fork) {            exec "what you really wanna do";            die "no exec";            # ... or ...            ## (some_perl_code_here)            exit 0;        }        exit 0;    }    waitpid($pid,0);
See also the perlipc manpage for more examples of forking and reapingmoribund children.

Note that if your forked child inherits system file descriptors likeSTDIN and STDOUT that are actually connected by a pipe or socket, evenif you exit, the remote server (such as, say, httpd or rsh) won't thinkyou're done. You should reopen those to /dev/null if it's any issue.

format
Declare a picture format with use by the write() function. Forexample:

    format Something =        Test: @<<<<<<<< @||||| @>>>>>              $str,     $%,    '$' . int($num)    .
    $str = "widget";    $num = $cost/$quantity;    $~ = 'Something';    write;
See the perlform manpage for many details and examples.
formline PICTURE,LIST
This is an internal function used by formats, though you may call ittoo. It formats (see the perlform manpage) a list of values according to thecontents of PICTURE, placing the output into the format outputaccumulator, $^A (or $ACCUMULATOR in English).Eventually, when a write() is done, the contents of$^A are written to some filehandle, but you could also read $^Ayourself and then set $^A back to "". Note that a format typicallydoes one formline() per line of form, but the formline() function itselfdoesn't care how many newlines are embedded in the PICTURE. This meansthat the ~ and ~~ tokens will treat the entire PICTURE as a single line.You may therefore need to use multiple formlines to implement a singlerecord format, just like the format compiler.

Be careful if you put double quotes around the picture, because an ``@''character may be taken to mean the beginning of an array name.formline() always returns TRUE. See the perlform manpage for other examples.

getc FILEHANDLE

getc
Returns the next character from the input file attached to FILEHANDLE,or a null string at end of file. If FILEHANDLE is omitted, reads from STDIN.This is not particularly efficient. It cannot be used to get unbufferedsingle-characters, however. For that, try something more like:

    if ($BSD_STYLE) {        system "stty cbreak </dev/tty >/dev/tty 2>&1";    }    else {        system "stty", '-icanon', 'eol', "\001";    }
    $key = getc(STDIN);
    if ($BSD_STYLE) {        system "stty -cbreak </dev/tty >/dev/tty 2>&1";    }    else {        system "stty", 'icanon', 'eol', '^@'; # ASCII null    }    print "\n";
Determination of whether $BSD_STYLE should be setis left as an exercise to the reader.

The POSIX::getattr() function can do this more portably on systemsalleging POSIX compliance.See also the Term::ReadKey module from your nearest CPAN site;details on CPAN can be found on the CPAN entry in the perlmod manpage.

getlogin
Returns the current login from /etc/utmp, if any. If null, usegetpwuid().

    $login = getlogin || getpwuid($<) || "Kilroy";
Do not consider getlogin() for authentication: it is not assecure as getpwuid().
getpeername SOCKET
Returns the packed sockaddr address of other end of the SOCKET connection.

    use Socket;    $hersockaddr    = getpeername(SOCK);    ($port, $iaddr) = unpack_sockaddr_in($hersockaddr);    $herhostname    = gethostbyaddr($iaddr, AF_INET);    $herstraddr     = inet_ntoa($iaddr);

getpgrp PID
Returns the current process group for the specified PID. Usea PID of 0 to get the current process group for thecurrent process. Will raise an exception if used on a machine thatdoesn't implement getpgrp(2). If PID is omitted, returns processgroup of current process. Note that the POSIX version of getpgrp()does not accept a PID argument, so only PID==0 is truly portable.
getppid
Returns the process id of the parent process.
getpriority WHICH,WHO
Returns the current priority for a process, a process group, or a user.(See the getpriority(2) manpage.) Will raise a fatal exception if used on amachine that doesn't implement getpriority(2).
getpwnam NAME

getgrnam NAME

gethostbyname NAME

getnetbyname NAME

getprotobyname NAME

getpwuid UID

getgrgid GID

getservbyname NAME,PROTO

gethostbyaddr ADDR,ADDRTYPE

getnetbyaddr ADDR,ADDRTYPE

getprotobynumber NUMBER

getservbyport PORT,PROTO

getpwent

getgrent

gethostent

getnetent

getprotoent

getservent

setpwent

setgrent

sethostent STAYOPEN

setnetent STAYOPEN

setprotoent STAYOPEN

setservent STAYOPEN

endpwent

endgrent

endhostent

endnetent

endprotoent

endservent
These routines perform the same functions as their counterparts in thesystem library. Within a list context, the return values from thevarious get routines are as follows:

    ($name,$passwd,$uid,$gid,       $quota,$comment,$gcos,$dir,$shell) = getpw*    ($name,$passwd,$gid,$members) = getgr*    ($name,$aliases,$addrtype,$length,@addrs) = gethost*    ($name,$aliases,$addrtype,$net) = getnet*    ($name,$aliases,$proto) = getproto*    ($name,$aliases,$port,$proto) = getserv*
(If the entry doesn't exist you get a null list.)

Within a scalar context, you get the name, unless the function was alookup by name, in which case you get the other thing, whatever it is.(If the entry doesn't exi

 
ICM Bot detect detector