In the syntax descriptions that follow, list operators that expect a list (and provide list context for the elements of the list) are shown with LIST as an argument. Such a list may consist of any combination of scalar arguments or list values; the list values will be included in the list as if each individual element were interpolated at that point 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 without parentheses around its arguments. (The syntax descriptions omit the parens.) If you use the parens, the simple (but occasionally surprising) rule is this: It LOOKS like a function, therefore it IS a function, and precedence doesn't matter. Otherwise it's a list operator or unary operator, and precedence does matter. And whitespace between the function and left parenthesis doesn't count---so you need to be careful sometimes:
print 1+2+3; # Prints 6. print(1+2) + 3; # Prints 3. print (1+2)+3; # Also prints 3! print +(1+2)+3; # Prints 6. print ((1+2)+3); # Prints 6.If you run Perl with the -w switch it can warn you about this. For example, 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, non-abortive failure is generally indicated in a scalar context by returning the undefined value, and in a list context by returning the null list.
Remember the following rule:
Each operator and function decides which sort of value it would be most
appropriate to return in a scalar context. Some operators return the
length of the list that would have been returned in a list context. Some
operators return the first value in the list. Some operators return the
last value in the list. Some operators return a count of successful
operations. In general, they do what you want, unless you want
consistency.
-r File is readable by effective uid/gid. -w File is writable by effective uid/gid. -x File is executable by effective uid/gid. -o File is owned by effective uid.
-R File is readable by real uid/gid. -W File is writable by real uid/gid. -X File is executable by real uid/gid. -O File is owned by real uid.
-e File exists. -z File has zero size. -s File has non-zero size (returns size).
-f File is a plain file. -d File is a directory. -l File is a symbolic link. -p File is a named pipe (FIFO). -S File is a socket. -b File is a block special file. -c File is a character special file. -t Filehandle is opened to a tty.
-u File has setuid bit set. -g File has setgid bit set. -k File has sticky bit set.
-T File is a text file. -B File is a binary file (opposite of -T).
-M Age of file in days when script started. -A Same for access time. -C Same for inode change time.The interpretation of the file permission operators -r, -R, -w, -W, -x and -X is based solely on the mode of the file and the uids and gids of the user. There may be other reasons you can't actually read, write or execute the file. Also note that, for the superuser, -r, -R, -w and -W always return 1, and -x and -X return 1 if any execute bit is set in the mode. Scripts run by the superuser may thus need to do a stat() in order to determine the actual mode of the file, or temporarily set the uid to something else.
Example:
while (<>) { chop; next unless -f $_; # ignore specials ... }Note that -s/a/b/ does not do a negated substitution. Saying -exp($foo) still works as expected, however---only single letters following a minus are interpreted as file tests.
The -T and -B switches work as follows. The first block or so of the file is examined for odd characters such as strange control codes or characters with the high bit set. If too many odd characters (>30%) are found, it's a -B file, otherwise it's a -T file. Also, any file containing null in the first block is considered a binary file. If -T or -B is used on a filehandle, the current stdio buffer is examined rather than the first block. Both -T and -B return TRUE on a null file, or a file at EOF when testing a filehandle.
If any of the file tests (or either the stat() or lstat() operators) are given the special filehandle consisting of a solitary underline, then the stat structure of the previous file test (or stat operator) is used, saving a system call. (This doesn't work with -t, and you need to remember that lstat() and -l will leave values in the stat structure for the symbolic link, not the real file.) Example:
print "Can do.\n" if -r $a || -w _ || -x _;
stat($filename); print "Readable\n" if -r _; print "Writable\n" if -w _; print "Executable\n" if -x _; print "Setuid\n" if -u _; print "Setgid\n" if -g _; print "Sticky\n" if -k _; print "Text\n" if -T _; print "Binary\n" if -B _;
For sleeps of finer granularity than one second, you may use Perl's
syscall() interface to access setitimer(2) if your system supports it,
or else see the select() entry elsewhere in this documentbelow.
($package, $filename, $line) = caller;With EXPR, it returns some extra information that the debugger uses to print a stack trace. The value of EXPR indicates how many call frames to go back before the current one.
($package, $filename, $line, $subroutine, $hasargs, $wantargs) = caller($i);Furthermore, when called from within the DB package, caller returns more detailed information: it sets sets the list variable @DB:args to be the arguments with which that subroutine was invoked.
$cnt = chmod 0755, 'foo', 'bar'; chmod 0755, @executables;
while (<>) { chomp; # avoid \n on last field @array = split(/:/); ... }You can actually chomp anything that's an lvalue, including an assignment:
chomp($cwd = `pwd`); chomp($answer = <STDIN>);If you chomp a list, each element is chomped, and the total number of characters removed is returned.
while (<>) { chop; # avoid \n on last field @array = split(/:/); ... }You can actually chop anything that's an lvalue, including an assignment:
chop($cwd = `pwd`); chop($answer = <STDIN>);If you chop a list, each element is chopped. Only the value of the last chop is returned.
Note that chop returns the last character. To return all but the last
character, use substr($string, 0, -1).
$cnt = chown $uid, $gid, 'foo', 'bar'; chown $uid, $gid, @filenames;Here's an example that looks up non-numeric uids in the passwd file:
print "User: "; chop($user = <STDIN>); print "Files: " chop($pattern = <STDIN>);
($login,$pass,$uid,$gid) = getpwnam($user) or die "$user not in passwd file";
@ary = <${pattern}>; # expand filenames chown $uid, $gid, @ary;
open(OUTPUT, '|sort >foo'); # pipe to sort ... # print stuff to output close OUTPUT; # wait for sort to finish open(INPUT, 'foo'); # get sort's resultsFILEHANDLE may be an expression whose value gives the real filehandle name.
Here's an example that makes sure that whoever runs this program knows their own password:
$pwd = (getpwuid($<))[1]; $salt = substr($pwd, 0, 2);
system "stty -echo"; print "Password: "; chop($word = <STDIN>); print "\n"; system "stty echo";
if (crypt($word, $salt) ne $pwd) { die "Sorry...\n"; } else { print "ok\n"; }Of course, typing in your own password to whoever asks you for it is unwise.
Breaks the binding between a DBM file and an associative array.
This binds a dbm(3) or ndbm(3) file to an associative array. ASSOC is the name of the associative array. (Unlike normal open, the first argument is NOT a filehandle, even though it looks like one). DBNAME is the name of the database (without the .dir or .pag extension). If the database does not exist, it is created with protection specified by MODE (as modified by the umask()). If your system only supports the older DBM functions, you may perform only one dbmopen() in your program. If your system has neither DBM nor ndbm, calling dbmopen() produces a fatal error.
If you don't have write access to the DBM file, you can only read associative array variables, not set them. If you want to test whether you can write, either use file tests or try setting a dummy array entry inside an eval(), which will trap the error.
Note that functions such as keys() and values() may return huge array values when used on large DBM files. You may prefer to use the each() function to iterate over large DBM files. Example:
# print out history file offsets dbmopen(%HIST,'/usr/lib/news/history',0666); while (($key,$val) = each %HIST) { print $key, ' = ', unpack('L',$val), "\n"; } dbmclose(%HIST);
When used on a hash array element, it tells you whether the value is defined, not whether the key exists in the hash. Use exists() for that.
Examples:
print if defined $switch{'D'}; print "$val\n" while defined($val = pop(@ary)); die "Can't readlink $sym: $!" unless defined($value = readlink $sym); eval '@foo = ()' if defined(@foo); die "No XYZ package defined" unless defined %_XYZ; sub foo { defined &$bar ? &$bar(@_) : die "No bar"; }See also undef().
The following deletes all the values of an associative array:
foreach $key (keys %ARRAY) { delete $ARRAY{$key}; }(But it would be faster to use the undef() command.) Note that the EXPR can be arbitrarily complicated as long as the final operation is a hash key lookup:
delete $ref->[$x][$y]{$key};
Equivalent examples:
die "Can't cd to spool: $!\n" unless chdir '/usr/spool/news'; chdir '/usr/spool/news' or die "Can't cd to spool: $!\n"If the value of EXPR does not end in a newline, the current script line number and input line number (if any) are also printed, and a newline is supplied. Hint: sometimes appending ``, stopped'' to your message will cause it to make better sense when the string ``at foo line 123'' is appended. Suppose you are running script ``canasta''.
die "/etc/games is no good"; die "/etc/games is no good, stopped";produce, respectively
/etc/games is no good at canasta line 123. /etc/games is no good, stopped at canasta line 123.See also exit() and warn().
do 'stat.pl';is just like
eval `cat stat.pl`;except that it's more efficient, more concise, keeps track of the current filename for error messages, and searches all the -I libraries if the file isn't in the current directory (see also the @INC array in the section on Predefined Names in the perlvar manpage). It's the same, however, in that it does reparse the file every time you call it, so you probably don't want to do this inside a loop.
Note that inclusion of library modules is better done with the
use() and require() operators.
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');
while (($key,$value) = each %ENV) { print "$key=$value\n"; }See also keys() and values().
An eof without an argument uses the last file read as argument. Empty parentheses () may be used to indicate the pseudo file formed of the files listed on the command line, i.e. eof() is reasonable to use inside a while (<>) loop to detect the end of only the last file. Use eof(ARGV) or eof without the parentheses to test EACH file in a while (<>) loop. Examples:
# reset line numbering on each input file while (<>) { print "$.\t$_"; close(ARGV) if (eof); # Not eof(). }
# insert dashes just before last line of last file while (<>) { if (eof()) { print "--------------\n"; close(ARGV); # close or break; is needed if we # are reading from the terminal } print; }Practical hint: you almost never need to use eof in Perl, because the input operators return undef when they run out of data.
If there is a syntax error or runtime error, or a die() statement is executed, an undefined value is returned by eval(), and $@ is set to the error message. If there was no error, $@ is guaranteed to be a null string. If EXPR is omitted, evaluates $_. The final semicolon, if any, may be omitted from the expression.
Note that, since eval() traps otherwise-fatal errors, it is useful for determining whether a particular feature (such as dbmopen() or symlink()) is implemented. It is also Perl's exception trapping mechanism, where the die operator is used to raise exceptions.
If the code to be executed doesn't vary, you may use the eval-BLOCK form to trap run-time errors without incurring the penalty of recompiling each time. The error, if any, is still returned in $@. Examples:
# make divide-by-zero non-fatal eval { $answer = $a / $b; }; warn $@ if $@;
# same thing, but less efficient eval '$answer = $a / $b'; warn $@ if $@;
# a compile-time error eval { $answer = };
# a run-time error eval '$answer ='; # sets $@With an eval(), you should be especially careful to remember what's being looked at when:
eval $x; # CASE 1 eval "$x"; # CASE 2
eval '$x'; # CASE 3 eval { $x }; # CASE 4
eval "\$$x++" # CASE 5 $$x++; # CASE 6Cases 1 and 2 above behave identically: they run the code contained in the variable $x. (Although case 2 has misleading double quotes making the reader wonder what else might be happening (nothing is).) Cases 3 and 4 likewise behave in the same way: they run the code <$x>, which does nothing at all. (Case 4 is preferred for purely visual reasons.) Case 5 is a place where normally you WOULD like to use double quotes, except in that particular situation, you can just use symbolic references instead, as in case 6.
If there is more than one argument in LIST, or if LIST is an array with more than one value, calls execvp(3) with the arguments in LIST. If there is only one scalar argument, the argument is checked for shell metacharacters. If there are any, the entire argument is passed to /bin/sh -c for parsing. If there are none, the argument is split into words and passed directly to execvp(), which is more efficient. Note: exec() (and system(0) 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 lie to the program you are executing about its own name, you can specify the program you actually want to run as an ``indirect object'' (without a comma) in front of the LIST. (This always forces interpretation of the LIST as a multi-valued list, even if there is only a single scalar in the list.) Example:
$shell = '/bin/csh'; exec $shell '-sh'; # pretend it's a login shellor, more directly,
exec {'/bin/csh'} '-sh'; # pretend it's a login shell
print "Exists\n" if exists $array{$key}; print "Defined\n" if defined $array{$key}; print "True\n" if $array{$key};A hash element can only be TRUE if it's defined, and defined if it exists, but the reverse doesn't necessarily hold true.
Note that the EXPR can be arbitrarily complicated as long as the final operation is a hash key lookup:
if (exists $ref->[$x][$y]{$key}) { ... }
$ans = <STDIN>; exit 0 if $ans =~ /^[Xx]/;See also die(). If EXPR is omitted, exits with 0 status.
use Fcntl;first to get the correct function definitions. Argument processing and value return works just like ioctl() below. Note that fcntl() will produce a fatal error if used on a machine that doesn't implement fcntl(2). For example:
use Fcntl; fcntl($filehandle, F_GETLK, $packed_return_buffer);
$LOCK_SH = 1; $LOCK_EX = 2; $LOCK_NB = 4; $LOCK_UN = 8;
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();Note that flock() can't lock things over the network. You need to do locking with fcntl() for that.
If you fork() without ever waiting on your children, you will accumulate zombies:
$SIG{'CHLD'} = sub { wait };There's also the double-fork trick (error checking on fork() 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);
Be careful if you put double quotes around the picture, since an ``@''
character may be taken to mean the beginning of an array name.
formline() always returns TRUE.
$login = getlogin || (getpwuid($<))[0] || "Kilroy";
# An internet sockaddr $sockaddr = 'S n a4 x8'; $hersockaddr = getpeername(S); ($family, $port, $heraddr) = unpack($sockaddr,$hersockaddr);
($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 a lookup by name, in which case you get the other thing, whatever it is. (If the entry doesn't exist you get the undefined value.) For example:
$uid = getpwnam $name = getpwuid $name = getpwent $gid = getgrnam $name = getgrgid $name = getgrent etc.The $members value returned by getgr*() is a space separated list of the login names of the members of the group.
For the gethost*() functions, if the h_errno variable is supported in C, it will be returned to you via $? if the function call fails. The @addrs value returned by a successful call is a list of the raw addresses returned by the corresponding system library call. In the Internet domain, each address is four bytes long and you can unpack it by saying something like:
($a,$b,$c,$d) = unpack('C4',$addr[0]);
# An internet sockaddr $sockaddr = 'S n a4 x8'; $mysockaddr = getsockname(S); ($family, $port, $myaddr) = unpack($sockaddr,$mysockaddr);
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time);All array elements are numeric, and come straight out of a struct tm. In particular this means that $mon has the range 0..11 and $wday has the range 0..6. If EXPR is omitted, does gmtime(time()).
The goto-EXPR form expects a label name, whose scope will be resolved dynamically. This allows for computed gotos per FORTRAN, but isn't necessarily recommended if you're optimizing for maintainability:
goto ("FOO", "BAR", "GLARCH")[$i];The goto-&NAME form is highly magical, and substitutes a call to the named subroutine for the currently running subroutine. This is used by AUTOLOAD subroutines that wish to load another subroutine and then pretend that the other subroutine had been called in the first place (except that any modifications to @_ in the current subroutine are propagated to the other subroutine.) After the goto, not even caller() will be able to tell that this routine was called first.
@foo = grep(!/^#/, @bar); # weed out commentsor equivalently,
@foo = grep {!/^#/} @bar; # weed out commentsNote that, since $_ is a reference into the list value, it can be used to modify the elements of the array. While this is useful and supported, it can cause bizarre results if the LIST is not a named array.
require "ioctl.ph"; # probably /usr/local/lib/perl/ioctl.phfirst to get the correct function definitions. If ioctl.ph doesn't exist or doesn't have the correct definitions you'll have to roll your own, based on your C header files such as <sys/ioctl.h>. (There is a Perl script called h2ph that comes with the Perl kit which may help you in this.) SCALAR will be read and/or written depending on the FUNCTION---a pointer to the string value of SCALAR will be passed as the third argument of the actual ioctl call. (If SCALAR has no string value but does have a numeric value, that 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 are useful for manipulating the values of structures used by ioctl(). The following example sets the erase character to DEL.
require 'ioctl.ph'; $sgttyb_t = "ccccs"; # 4 chars and a short if (ioctl(STDIN,$TIOCGETP,$sgttyb)) { @ary = unpack($sgttyb_t,$sgttyb); $ary[2] = 127; $sgttyb = pack($sgttyb_t,@ary); ioctl(STDIN,$TIOCSETP,$sgttyb) || die "Can't ioctl: $!"; }The return value of ioctl (and fcntl) is as follows:
if OS returns: then Perl returns: -1 undefined value 0 string "0 but true" anything else that numberThus Perl returns TRUE on success and FALSE on failure, yet you can still easily determine the actual value returned by the operating system:
($retval = ioctl(...)) || ($retval = -1); printf "System returned %d\n", $retval;
$_ = join(':', $login,$passwd,$uid,$gid,$gcos,$home,$shell);See the split entry in the perlfunc manpage.
@keys = keys %ENV; @values = values %ENV; while ($#keys >= 0) { print pop(@keys), '=', pop(@values), "\n"; }or how about sorted by key:
foreach $key (sort(keys %ENV)) { print $key, '=', $ENV{$key}, "\n"; }
$cnt = kill 1, $child1, $child2; kill 9, @goners;Unlike in the shell, in Perl if the SIGNAL is negative, it kills process groups instead of processes. (On System V, a negative PROCESS number will also kill process groups, but that's not portable.) That means you usually want to use positive not negative signals. You may also use a signal name in quotes.
line: while (<STDIN>) { last line if /^$/; # exit when done with header ... }
A local modifies the listed variables to be local to the enclosing block, subroutine, eval or ``do''. If more than one value is listed, the list must be placed in parens. All the listed elements must be legal lvalues. This operator works by saving the current values of those variables in LIST on a hidden stack and restoring them upon exiting the block, subroutine or eval. This means that called subroutines can also reference the local variable, but not the global one. The LIST may be assigned to if desired, which allows you to initialize your local variables. (If no initializer is given for a particular variable, it is created with an undefined value.) Commonly this is used to name the parameters to a subroutine. Examples:
sub RANGEVAL { local($min, $max, $thunk) = @_; local $result = ''; local $i;
# Presumably $thunk makes reference to $i
for ($i = $min; $i < $max; $i++) { $result .= eval $thunk; }
$result; }
if ($sw eq '-v') { # init local array with global array local @ARGV = @ARGV; unshift(@ARGV,'echo'); system @ARGV; } # @ARGV restored
# temporarily add to digits associative array if ($base12) { # (NOTE: not claiming this is efficient!) local(%digits) = (%digits,'t',10,'e',11); parse_num(); }Note that local() is a run-time command, and so gets executed every time through a loop. In Perl 4 it used more stack storage each time until the loop was exited. Perl 5 reclaims the space each time through, but it's still more efficient to declare your variables outside the loop.
A local is simply a modifier on an lvalue expression. When you assign to a localized EXPR, the local doesn't change whether EXPR is viewed as a scalar or an array. So
local($foo) = <STDIN>; local @FOO = <STDIN>;both supply a list context to the righthand side, while
local $foo = <STDIN>;supplies a scalar context.
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);All array elements are numeric, and come straight out of a struct tm. In particular this means that $mon has the range 0..11 and $wday has the range 0..6. If EXPR is omitted, does localtime(time).
In a scalar context, prints out the ctime(3) value:
$now_string = localtime; # e.g. "Thu Oct 13 04:54:34 1994"See also the timelocal entry in the perlmod manpage and the strftime(3) function available via the POSIX modulie.
@chars = map(chr, @nums);translates a list of numbers to the corresponding characters. And
%hash = map {&key($_), $_} @array;is just a funny way to write
%hash = (); foreach $_ (@array) { $hash{&key($_)} = $_; }
my $_; # Illegal.Unlike the ``local'' declaration, variables declared with ``my'' are totally hidden from the outside world, including any called subroutines (even if it's the same subroutine---every call gets its own copy).
(An eval(), however, can see the lexical variables of the scope it is being evaluated in so long as the names aren't hidden by declarations within the eval() itself. See the perlref manpage.)
The EXPR may be assigned to if desired, which allows you to initialize your variables. (If no initializer is given for a particular variable, it is created with an undefined value.) Commonly this is used to name the parameters to a subroutine. Examples:
sub RANGEVAL { my($min, $max, $thunk) = @_; my $result = ''; my $i;
# Presumably $thunk makes reference to $i
for ($i = $min; $i < $max; $i++) { $result .= eval $thunk; }
$result; }
if ($sw eq '-v') { # init my array with global array my @ARGV = @ARGV; unshift(@ARGV,'echo'); system @ARGV; } # Outer @ARGV again visibleThe ``my'' is simply a modifier on something you might assign to. So when you do assign to the EXPR, the ``my'' doesn't change whether EXPR is viewed as a scalar or an array. So
my ($foo) = <STDIN>; my @FOO = <STDIN>;both supply a list context to the righthand side, while
my $foo = <STDIN>;supplies a scalar context. But the following only declares one variable:
my $foo, $bar = 1;That has the same effect as
my $foo; $bar = 1;The declared variable is not introduced (is not visible) until after the current statement. Thus,
my $x = $x;can be used to initialize the new $x with the value of the old $x, and the expression
my $x = 123 and $x == 123is false unless the old $x happened to have the value 123.
Some users may wish to encourage the use of lexically scoped variables. As an aid to catching implicit references to package variables, if you say
use strict 'vars';then any variable reference from there to the end of the enclosing block must either refer to a lexical variable, or must be fully qualified with the package name. A compilation error results otherwise. An inner block may countermand this with ``no strict `vars'''.
line: while (<STDIN>) { next line if /^#/; # discard comments ... }Note that if there were a continue block on the above, it would get executed even on discarded lines. If the LABEL is omitted, the command refers to the innermost enclosing loop.
$val = oct($val) if $val =~ /^0/;If EXPR is omitted, uses $_.
$ARTICLE = 100; open ARTICLE or die "Can't find article $ARTICLE: $!\n"; while (<ARTICLE>) {...
open(LOG, '>>/usr/spool/news/twitlog'); # (log is reserved)
open(article, "caesar <$article |"); # decrypt article
open(extract, "|sort >/tmp/Tmp$$"); # $$ is our process id
# process argument list of files along with any includes
foreach $file (@ARGV) { process($file, 'fh00'); }
sub process { local($filename, $input) = @_; $input++; # this is a string increment unless (open($input, $filename)) { print STDERR "Can't open $filename: $!\n"; return; }
while (<$input>) { # note use of indirection if (/^#include "(.*)"/) { process($1, $input); next; } ... # whatever } }You may also, in the Bourne shell tradition, specify an EXPR beginning with ``>&'', in which case the rest of the string is interpreted as the name of a filehandle (or file descriptor, if numeric) which is to be duped and opened. You may use & after >, >>, <, +>, +>> and +<. The mode you specify should match the mode of the original filehandle. Here is a script that saves, redirects, and restores STDOUT and STDERR:
#!/usr/bin/perl open(SAVEOUT, ">&STDOUT"); open(SAVEERR, ">&STDERR");
open(STDOUT, ">foo.out") || die "Can't redirect stdout"; open(STDERR, ">&STDOUT") || die "Can't dup stdout";
select(STDERR); $| = 1; # make unbuffered select(STDOUT); $| = 1; # make unbuffered
print STDOUT "stdout 1\n"; # this works for print STDERR "stderr 1\n"; # subprocesses too
close(STDOUT); close(STDERR);
open(STDOUT, ">&SAVEOUT"); open(STDERR, ">&SAVEERR");
print STDOUT "stdout 2\n"; print STDERR "stderr 2\n";If you specify ``<&=N'', where N is a number, then Perl will do an equivalent of C's fdopen() of that file descriptor. For example:
open(FILEHANDLE, "<&=$fd")If you open a pipe on the command ``-'', i.e. either ``|-'' or ``-|'', then there is an implicit fork done, and the return value of open is the pid of the child within the parent process, and 0 within the child process. (Use defined($pid) to determine whether the open was successful.) The filehandle behaves normally for the parent, but i/o to that filehandle is piped from/to the STDOUT/STDIN of the child process. In the child process the filehandle isn't opened---i/o happens from/to the new STDOUT or STDIN. Typically this is used like the normal piped open when you want to exercise more control over just how the pipe command gets executed, such as when you are running setuid, and don't want to have to scan shell commands for metacharacters. The following pairs are more or less equivalent:
open(FOO, "|tr '[a-z]' '[A-Z]'"); open(FOO, "|-") || exec 'tr', '[a-z]', '[A-Z]';
open(FOO, "cat -n '$file'|"); open(FOO, "-|") || exec 'cat', '-n', $file;Explicitly closing any piped filehandle causes the parent process to wait for the child to finish, and returns the status value in $?. Note: on any operation which may do a fork, unflushed buffers remain unflushed in both processes, which means you may need to set $| to avoid duplicate output.
The filename that is passed to open will have leading and trailing whitespace deleted. In order to open a file with arbitrary weird characters in it, it's necessary to protect any leading and trailing whitespace thusly:
$file =~ s#^(\s)#./$1#; open(FOO, "< $file\0");
A An ascii string, will be space padded. a An ascii string, will be null padded. b A bit string (ascending bit order, like vec()). B A bit string (descending bit order). h A hex string (low nybble first). H A hex string (high nybble first).
c A signed char value. C An unsigned char value. s A signed short value. S An unsigned short value. i A signed integer value. I An unsigned integer value. l A signed long value. L An unsigned long value.
n A short in "network" order. N A long in "network" order. v A short in "VAX" (little-endian) order. V A long in "VAX" (little-endian) order.
f A single-precision float in the native format. d A double-precision float in the native format.
p A pointer to a null-terminated string. P A pointer to a structure (fixed-length string).
u A uuencoded string.
x A null byte. X Back up a byte. @ Null fill to absolute position.Each letter may optionally be followed by a number which gives a repeat count. With all types except ``a'', ``A'', ``b'', ``B'', ``h'' and ``H'', and ``P'' the pack function will gobble up that many values from the LIST. A * for the repeat count means to use however many items are left. The ``a'' and ``A'' types gobble just one value, but pack it as a string of length count, padding with nulls or spaces as necessary. (When unpacking, ``A'' strips trailing spaces and nulls, but ``a'' does not.) Likewise, the ``b'' and ``B'' fields pack a string that many bits long. The ``h'' and ``H'' fields pack a string that many nybbles long. The ``P'' packs a pointer to a structure of the size indicated by the length. Real numbers (floats and doubles) are in the native machine format only; due to the multiplicity of floating formats around, and the lack of a standard ``network'' representation, no facility for interchange has been made. This means that packed floating point data written on one machine may not be readable on another - even if both use IEEE floating point arithmetic (as the endian-ness of the memory representation is not part of the IEEE spec). Note that Perl uses doubles internally for all numeric calculation, and converting from double into float and thence back to double again will lose precision (i.e. unpack("f", pack("f", $foo)) will not in general equal $foo).
Examples:
$foo = pack("cccc",65,66,67,68); # foo eq "ABCD" $foo = pack("c4",65,66,67,68); # same thing
$foo = pack("ccxxcc",65,66,67,68); # foo eq "AB\0\0CD"
$foo = pack("s2",1,2); # "\1\0\2\0" on little-endian # "\0\1\0\2" on big-endian
$foo = pack("a4","abcd","x","y","z"); # "abcd"
$foo = pack("aaaa","abcd","x","y","z"); # "axyz"
$foo = pack("a14","abcdefg"); # "abcdefg\0\0\0\0\0\0\0"
$foo = pack("i9pl", gmtime); # a real struct tm (on my system anyway)
sub bintodec { unpack("N", pack("B32", substr("0" x 32 . shift, -32))); }The same template may generally also be used in the unpack function.
$tmp = $ARRAY[$#ARRAY--];If there are no elements in the array, returns the undefined value.
for $value (LIST) { $ARRAY[++$#ARRAY] = $value; }but is more efficient. Returns the new number of elements in the array.
(Note: if your rand function consistently returns numbers that are too
large or too small, then your version of Perl was probably compiled
with the wrong number of RANDBITS. As a workaround, you can usually
multiply EXPR by the correct power of 2 to get the range you want.
This will make your script unportable, however. It's better to recompile
if you can.)
# a simpleminded Pascal comment stripper # (warning: assumes no { or } in strings) line: while (<STDIN>) { while (s|({.*}.*){.*}|$1 |) {} s|{.*}| |; if (s|{.*| |) { $front = $_; while (<STDIN>) { if (/}/) { # end of comment? s|^|$front{|; redo line; } } } print; }
REF SCALAR ARRAY HASH CODE GLOBIf the referenced object has been blessed into a package, then that package name is returned instead. You can think of ref() as a typeof() operator.
if (ref($r) eq "HASH") { print "r is a reference to an associative array.\n"; } if (!ref ($r) { print "r is not a reference at all.\n"; }See also the perlref manpage.
Otherwise, demands that a library file be included if it hasn't already been included. The file is included via the do-FILE mechanism, which is essentially just a variety of eval(). Has semantics similar to the following subroutine:
sub require { local($filename) = @_; return 1 if $INC{$filename}; local($realfilename,$result); ITER: { foreach $prefix (@INC) { $realfilename = "$prefix/$filename"; if (-f $realfilename) { $result = do $realfilename; last ITER; } } die "Can't find $filename in \@INC"; } die $@ if $@; die "$filename did not return true value" unless $result; $INC{$filename} = $realfilename; $result; }Note that the file will not be included twice under the same specified name. The file must return TRUE as the last statement to indicate successful execution of any initialization code, so it's customary to end such a file with ``1;'' unless you're sure it'll return TRUE otherwise. But it's better just to put the ``1;'', in case you add more statements.
If EXPR is a bare word, the require assumes a ``.pm'' extension for you, to make it easy to load standard modules. This form of loading of modules does not risk altering your namespace.
For a yet-more-powerful import facility, see the the use() entry elsewhere in this documentthe perlmod manpage.
reset 'X'; # reset all X variables reset 'a-z'; # reset lower case variables reset; # just reset ?? searchesResetting ``A-Z'' is not recommended since you'll wipe out your ARGV and ENV arrays. Only resets package variables---lexical variables are unaffected, but they clean themselves up on scope exit anyway, so anymore you probably want to use them instead. See the my entry elsewhere in this document.
select(REPORT1); $^ = 'report1_top'; select(REPORT2); $^ = 'report2_top';FILEHANDLE may be an expression whose value gives the name of the actual filehandle. Thus:
$oldfh = select(STDERR); $| = 1; select($oldfh);With Perl 5, filehandles are objects with methods, and the last example is preferably written
use FileHandle; STDERR->autoflush(1);
$rin = $win = $ein = ''; vec($rin,fileno(STDIN),1) = 1; vec($win,fileno(STDOUT),1) = 1; $ein = $rin | $win;If you want to select on many filehandles you might wish to write a subroutine:
sub fhbits { local(@fhlist) = split(' ',$_[0]); local($bits); for (@fhlist) { vec($bits,fileno($_),1) = 1; } $bits; } $rin = &fhbits('STDIN TTY SOCK');The usual idiom is:
($nfound,$timeleft) = select($rout=$rin, $wout=$win, $eout=$ein, $timeout);or to block until something becomes ready:
$nfound = select($rout=$rin, $wout=$win, $eout=$ein, undef);Any of the bitmasks can also be undef. The timeout, if specified, is in seconds, which may be fractional. Note: not all implementations are capable of returning the $timeleft. If not, they always return $timeleft equal to the supplied $timeout.
You can effect a 250 microsecond sleep this way:
select(undef, undef, undef, 0.25);
$semop = pack("sss", $semnum, -1, 0); die "Semaphore trouble: $!\n" unless semop($semid, $semop);To signal the semaphore, replace ``-1'' with ``1''.
On some older systems, it may sleep up to a full second less than what
you requested, depending on how it counts seconds. Most modern systems
always sleep the full amount.
In the interests of efficiency the normal calling code for subroutines is bypassed, with the following effects: the subroutine may not be a recursive subroutine, and the two elements to be compared are passed into the subroutine not via @_ but as $a and $b (see example below). They are passed by reference, so don't modify $a and $b.
Examples:
# sort lexically @articles = sort @files;
# same thing, but with explicit sort routine @articles = sort {$a cmp $b} @files;
# same thing in reversed order @articles = sort {$b cmp $a} @files;
# sort numerically ascending @articles = sort {$a <=> $b} @files;
# sort numerically descending @articles = sort {$b <=> $a} @files;
# sort using explicit subroutine name sub byage { $age{$a} <=> $age{$b}; # presuming integers } @sortedclass = sort byage @class;
sub backwards { $b cmp $a; } @harry = ('dog','cat','x','Cain','Abel'); @george = ('gone','chased','yz','Punished','Axed'); print sort @harry; # prints AbelCaincatdogx print sort backwards @harry; # prints xdogcatCainAbel print sort @george, 'to', @harry; # prints AbelAxedCainPunishedcatchaseddoggonetoxyz
push(@a,$x,$y) splice(@a,$#a+1,0,$x,$y) pop(@a) splice(@a,-1) shift(@a) splice(@a,0,1) unshift(@a,$x,$y) splice(@a,0,0,$x,$y) $a[$x] = $y splice(@a,$x,1,$y);Example, assuming array lengths are passed before arrays:
sub aeq { # compare two list values local(@a) = splice(@_,0,shift); local(@b) = splice(@_,0,shift); return 0 unless @a == @b; # same len? while (@a) { return 0 if pop(@a) ne pop(@b); } return 1; } if (&aeq($len,@foo[1..$len],0+@bar,@bar)) { ... }
If not in a list context, returns the number of fields found and splits into the @_ array. (In a list context, you can force the split into @_ by using ?? as the pattern delimiters, but it still returns the array value.) The use of implicit split to @_ is deprecated, however.
If EXPR is omitted, splits the $_ string. If PATTERN is also omitted, splits on whitespace (after skipping any leading whitespace). Anything matching PATTERN is taken to be a delimiter separating the fields. (Note that the delimiter may be longer than one character.) If LIMIT is specified and is not negative, splits into no more than that many fields (though it may split into fewer). If LIMIT is unspecified, trailing null fields are stripped (which potential users of pop() would do well to remember). If LIMIT is negative, it is treated as if an arbitrarily large LIMIT had been specified.
A pattern matching the null string (not to be confused with a null pattern //, which is just one member of the set of patterns matching a null string) will split the value of EXPR into separate characters at each point it matches that way. For example:
print join(':', split(/ */, 'hi there'));produces the output `h:i:t:h:e:r:e'.
The LIMIT parameter can be used to partially split a line
($login, $passwd, $remainder) = split(/:/, $_, 3);When assigning to a list, if LIMIT is omitted, Perl supplies a LIMIT one larger than the number of variables in the list, to avoid unnecessary work. For the list above LIMIT would have been 4 by default. In time critical applications it behooves you not to split into more fields than you really need.
If the PATTERN contains parentheses, additional array elements are created from each matching substring in the delimiter.
split(/([,-])/, "1-10,20");produces the list value
(1, '-', 10, ',', 20)The pattern /PATTERN/ may be replaced with an expression to specify patterns that vary at runtime. (To do runtime compilation only once, use /$variable/o.)
As a special case, specifying a PATTERN of space (' ') will split on white space just as split with no arguments does. Thus, split(' `) can be used to emulate awk's default behavior, whereas split(/ /) will give you as many null initial fields as there are leading spaces. A split on /\s+/ is like a split(' `) except that any leading whitespace produces a null first field. A split with no arguments really does a split(' ', $_) internally.
Example:
open(passwd, '/etc/passwd'); while (<passwd>) { ($login, $passwd, $uid, $gid, $gcos, $home, $shell) = split(/:/); ... }(Note that $shell above will still have a newline on it. See the chop, chomp, and join entries elsewhere in this document.)
($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size, $atime,$mtime,$ctime,$blksize,$blocks) = stat($filename);If stat is passed the special filehandle consisting of an underline, no stat is done, but the current contents of the stat structure from the last stat or filetest are returned. Example:
if (-x $file && (($d) = stat(_)) && $d < 0) { print "$file is executable NFS file\n"; }(This only works on machines for which the device number is negative under NFS.)
For example, here is a loop which inserts index producing entries before any line containing a certain pattern:
while (<>) { study; print ".IX foo\n" if /\bfoo\b/; print ".IX bar\n" if /\bbar\b/; print ".IX blurfl\n" if /\bblurfl\b/; ... print; }In searching for /\bfoo\b/, only those locations in $_ that contain ``f'' will be looked at, because ``f'' is rarer than ``o''. In general, this is a big win except in pathological cases. The only question is whether it saves you more time than it took to build the linked list in the first place.
Note that if you have to look for strings that you don't know till runtime, you can build an entire loop as a string and eval that to avoid recompiling all your patterns all the time. Together with undefining $/ to input entire files as one record, this can be very fast, often faster than specialized programs like fgrep(1). The following scans a list of files (@files) for a list of words (@words), and prints out the names of those files that contain a match:
$search = 'while (<>) { study;'; foreach $word (@words) { $search .= "++\$seen{\$ARGV} if /\\b$word\\b/;\n"; } $search .= "}"; @ARGV = @files; undef $/; eval $search; # this screams $/ = "\n"; # put back to normal input delim foreach $file (sort keys(%seen)) { print $file, "\n"; }
You can use the substr() function
as an lvalue, in which case EXPR must be an lvalue. If you assign
something shorter than LEN, the string will shrink, and if you assign
something longer than LEN, the string will grow to accommodate it. To
keep the string the same length you may need to pad or chop your value
using sprintf().
$symlink_exists = (eval 'symlink("","");', $@ eq '');
require 'syscall.ph'; # may need to run h2ph syscall(&SYS_write, fileno(STDOUT), "hi there\n", 9);Note that Perl only supports passing of up to 14 arguments to your system call, which in practice should usually suffice.
Note that functions such as keys() and values() may return huge array values when used on large objects, like DBM files. You may prefer to use the each() function to iterate over such. Example:
# print out history file offsets tie(%HIST, NDBM_File, '/usr/lib/news/history', 1, 0); while (($key,$val) = each %HIST) { print $key, ' = ', unpack('L',$val), "\n"; } untie(%HIST);A package implementing an associative array should have the following methods:
TIEHASH objectname, LIST DESTROY this FETCH this, key STORE this, key, value DELETE this, key EXISTS this, key FIRSTKEY this NEXTKEY this, lastkeyA package implementing an ordinary array should have the following methods:
TIEARRAY objectname, LIST DESTROY this FETCH this, key STORE this, key, value [others TBD]A package implementing a scalar should have the following methods:
TIESCALAR objectname, LIST DESTROY this FETCH this, STORE this, value
($user,$system,$cuser,$csystem) = times;
undef $foo; undef $bar{'blurfl'}; undef @ary; undef %assoc; undef &mysub; return (wantarray ? () : undef) if $they_blew_it;
$cnt = unlink 'a', 'b', 'c'; unlink @goners; unlink <*.bak>;Note: unlink will not delete directories unless you are superuser and the -U flag is supplied to Perl. Even if these conditions are met, be warned that unlinking a directory can inflict damage on your filesystem. Use rmdir instead.
sub substr { local($what,$where,$howmuch) = @_; unpack("x$where a$howmuch", $what); }and then there's
sub ordinal { unpack("c",$_[0]); } # same as ord()In addition, you may prefix a field with a %<number> to indicate that you want a <number>-bit checksum of the items instead of the items themselves. Default is a 16-bit checksum. For example, the following computes the same number as the System V sum program:
while (<>) { $checksum += unpack("%16C*", $_); } $checksum %= 65536;The following efficiently counts the number of set bits in a bit vector:
$setbits = unpack("%32b*", $selectmask);
unshift(ARGV, '-e') unless $ARGV[0] =~ /^-/;Note the LIST is prepended whole, not one element at a time, so the prepended elements stay in the same order. Use reverse to do the reverse.
BEGIN { require Module; import Module LIST; }If you don't want your namespace altered, use require instead.
The BEGIN forces the require and import to happen at compile time. The require makes sure the module is loaded into memory if it hasn't been yet. The import is not a builtin---it's just an ordinary static method call into the ``Module'' package to tell the module to import the list of features back into the current package. The module can implement its import method any way it likes, though most modules just choose to derive their import method via inheritance from the Exporter class that is defined in the Exporter module.
Because this is a wide-open interface, pragmas (compiler directives) are also implemented this way. Currently implemented pragmas are:
use integer; use sigtrap qw(SEGV BUS); use strict qw(subs vars refs); use subs qw(afunc blurfl);These pseudomodules import semantics into the current block scope, unlike ordinary modules, which import symbols into the current package (which are effective through the end of the file).
There's a corresponding ``no'' command that unimports meanings imported by use.
no integer; no strict 'refs';See the perlmod manpage for a list of standard modules and pragmas.
#!/usr/bin/perl $now = time; utime $now, $now, @ARGV;
Vectors created with vec() can also be manipulated with the logical operators |, & and ^, which will assume a bit vector operation is desired when both operands are strings.
To transform a bit vector into a string or array of 0's and 1's, use these:
$bits = unpack("b*", $vector); @bits = split(//, unpack("b*", $vector));If you know the exact length in bits, it can be used in place of the *.
use POSIX "wait_h"; ... waitpid(-1,&WNOHANG);then you can do a non-blocking wait for any process. Non-blocking wait is only available on machines supporting either the waitpid(2) or wait4(2) system calls. However, waiting for a particular pid with FLAGS of 0 is implemented everywhere. (Perl emulates the system call by remembering the status values of processes that have exited but have not been harvested by the Perl script yet.)
return wantarray ? () : undef;
Top of form processing is handled automatically: if there is insufficient room on the current page for the formatted record, the page is advanced by writing a form feed, a special top-of-page format is used to format the new page header, and then the record is written. By default the top-of-page format is the name of the filehandle with ``_TOP'' appended, but it may be dynamically set to the format of your choice by assigning the name to the $^ variable while the filehandle is selected. The number of lines remaining on the current page is in variable $-, which can be set to 0 to force a new page.
If FILEHANDLE is unspecified, output goes to the current default output channel, which starts out as STDOUT but may be changed by the select operator. If the FILEHANDLE is an EXPR, then the expression is evaluated and the resulting string is used to look up the name of the FILEHANDLE at run time. For more on formats, see the perlform manpage.
Note that write is NOT the opposite of read. Unfortunately.