[comp.sys.amiga] Perl now available for amiga.

rminnich@udel.EDU (Ron Minnich) (04/23/88)

I am posting perl to comp.binaries.amiga. It is a real nice language.
It is interpretive and has a symbolic debugger.

Here is an example, an egrep (with emacs-style expressions). 
ON unix it runs half as fast as grep, on the amiga it is limited
by disk throughput. It takes the usual:
egrep pattern [list-of-files]

#!/usr/bin/perl
die "Usage: $0 pattern [files]" unless $#ARGV > -1;

$pat=$ARGV[0];
shift;

while (<>) {
  /$pat/ && (print);
}

And here is the man page.

.rn '' }`
''' $Header: perl.man.1,v 1.0.1.7 88/03/02 12:36:18 root Exp $
''' 
''' $Log:	perl.man.1,v $
''' Revision 1.0.1.7  88/03/02  12:36:18  root
''' patch24: documented file tests
''' 
''' Revision 1.0.1.6  88/02/25  11:42:26  root
''' patch23: two typos and an omission.
''' 
''' Revision 1.0.1.5  88/02/12  10:26:35  root
''' patch22: some systems don't have \(bs
''' 
''' Revision 1.0.1.4  88/02/06  00:19:44  root
''' patch21: documented -v, /foo/i.
''' 
''' Revision 1.0.1.3  88/02/04  17:48:02  root
''' patch20: added missing chop($user); to example in chown.
''' 
''' Revision 1.0.1.2  88/01/30  17:04:07  root
''' patch 11: random cleanup
''' 
''' Revision 1.0.1.1  88/01/28  10:24:44  root
''' patch8: added eval operator.
''' 
''' Revision 1.0  87/12/18  16:18:16  root
''' Initial revision
''' 
''' 
.de Sh
.br
.ne 5
.PP
\fB\\$1\fR
.PP
..
.de Sp
.if t .sp .5v
.if n .sp
..
.de Ip
.br
.ie \\n.$>=3 .ne \\$3
.el .ne 3
.IP "\\$1" \\$2
..
'''
'''     Set up \*(-- to give an unbreakable dash;
'''     string Tr holds user defined translation string.
'''     Bell System Logo is used as a dummy character.
'''
.tr \(*W-|\(bv\*(Tr
.ie n \{\
.ds -- \(*W-
.if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
.if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch
.ds L" ""
.ds R" ""
.ds L' '
.ds R' '
'br\}
.el\{\
.ds -- \(em\|
.tr \*(Tr
.ds L" ``
.ds R" ''
.ds L' `
.ds R' '
'br\}
.TH PERL 1 LOCAL
.SH NAME
perl - Practical Extraction and Report Language
.SH SYNOPSIS
.B perl [options] filename args
.SH DESCRIPTION
.I Perl
is a interpreted language optimized for scanning arbitrary text files,
extracting information from those text files, and printing reports based
on that information.
It's also a good language for many system management tasks.
The language is intended to be practical (easy to use, efficient, complete)
rather than beautiful (tiny, elegant, minimal).
It combines (in the author's opinion, anyway) some of the best features of C,
\fIsed\fR, \fIawk\fR, and \fIsh\fR,
so people familiar with those languages should have little difficulty with it.
(Language historians will also note some vestiges of \fIcsh\fR, Pascal, and
even BASIC-PLUS.)
Expression syntax corresponds quite closely to C expression syntax.
If you have a problem that would ordinarily use \fIsed\fR
or \fIawk\fR or \fIsh\fR, but it
exceeds their capabilities or must run a little faster,
and you don't want to write the silly thing in C, then
.I perl
may be for you.
There are also translators to turn your sed and awk scripts into perl scripts.
OK, enough hype.
.PP
Upon startup,
.I perl
looks for your script in one of the following places:
.Ip 1. 4 2
Specified line by line via
.B \-e
switches on the command line.
.Ip 2. 4 2
Contained in the file specified by the first filename on the command line.
(Note that systems supporting the #! notation invoke interpreters this way.)
.Ip 3. 4 2
Passed in via standard input.
.PP
After locating your script,
.I perl
compiles it to an internal form.
If the script is syntactically correct, it is executed.
.Sh "Options"
Note: on first reading this section may not make much sense to you.  It's here
at the front for easy reference.
.PP
A single-character option may be combined with the following option, if any.
This is particularly useful when invoking a script using the #! construct which
only allows one argument.  Example:
.nf

.ne 2
	#!/bin/perl -spi.bak	# same as -s -p -i.bak
	.\|.\|.

.fi
Options include:
.TP 5
.B \-D<number>
sets debugging flags.
To watch how it executes your script, use
.B \-D14.
(This only works if debugging is compiled into your
.IR perl .)
.TP 5
.B \-e commandline
may be used to enter one line of script.
Multiple
.B \-e
commands may be given to build up a multi-line script.
If
.B \-e
is given,
.I perl
will not look for a script filename in the argument list.
.TP 5
.B \-i<extension>
specifies that files processed by the <> construct are to be edited
in-place.
It does this by renaming the input file, opening the output file by the
same name, and selecting that output file as the default for print statements.
The extension, if supplied, is added to the name of the
old file to make a backup copy.
If no extension is supplied, no backup is made.
Saying \*(L"perl -p -i.bak -e "s/foo/bar/;" ... \*(R" is the same as using
the script:
.nf

.ne 2
	#!/bin/perl -pi.bak
	s/foo/bar/;

which is equivalent to

.ne 14
	#!/bin/perl
	while (<>) {
		if ($ARGV ne $oldargv) {
			rename($ARGV,$ARGV . '.bak');
			open(ARGVOUT,">$ARGV");
			select(ARGVOUT);
			$oldargv = $ARGV;
		}
		s/foo/bar/;
	}
	continue {
	    print;	# this prints to original filename
	}
	select(stdout);

.fi
except that the \-i form doesn't need to compare $ARGV to $oldargv to know when
the filename has changed.
It does, however, use ARGVOUT for the selected filehandle.
Note that stdout is restored as the default output filehandle after the loop.
.TP 5
.B \-I<directory>
may be used in conjunction with
.B \-P
to tell the C preprocessor where to look for include files.
By default /usr/include and /usr/lib/perl are searched.
.TP 5
.B \-n
causes
.I perl
to assume the following loop around your script, which makes it iterate
over filename arguments somewhat like \*(L"sed -n\*(R" or \fIawk\fR:
.nf

.ne 3
	while (<>) {
		...		# your script goes here
	}

.fi
Note that the lines are not printed by default.
See
.B \-p
to have lines printed.
.TP 5
.B \-p
causes
.I perl
to assume the following loop around your script, which makes it iterate
over filename arguments somewhat like \fIsed\fR:
.nf

.ne 5
	while (<>) {
		...		# your script goes here
	} continue {
		print;
	}

.fi
Note that the lines are printed automatically.
To suppress printing use the
.B \-n
switch.
A
.B \-p
overrides a
.B \-n
switch.
.TP 5
.B \-P
causes your script to be run through the C preprocessor before
compilation by
.I perl.
(Since both comments and cpp directives begin with the # character,
you should avoid starting comments with any words recognized
by the C preprocessor such as \*(L"if\*(R", \*(L"else\*(R" or \*(L"define\*(R".)
.TP 5
.B \-s
enables some rudimentary switch parsing for switches on the command line
after the script name but before any filename arguments (or before a --).
Any switch found there is removed from @ARGV and sets the corresponding variable in the
.I perl
script.
The following script prints \*(L"true\*(R" if and only if the script is
invoked with a -xyz switch.
.nf

.ne 2
	#!/bin/perl -s
	if ($xyz) { print "true\en"; }

.fi
.TP 5
.B \-v
prints the version and patchlevel of your perl executable.
.Sh "Data Types and Objects"
.PP
Perl has about two and a half data types: strings, arrays of strings, and
associative arrays.
Strings and arrays of strings are first class objects, for the most part,
in the sense that they can be used as a whole as values in an expression.
Associative arrays can only be accessed on an association by association basis;
they don't have a value as a whole (at least not yet).
.PP
Strings are interpreted numerically as appropriate.
A string is interpreted as TRUE in the boolean sense if it is not the null
string or 0.
Booleans returned by operators are 1 for true and '0' or '' (the null
string) for false.
.PP
References to string variables always begin with \*(L'$\*(R', even when referring
to a string that is part of an array.
Thus:
.nf

.ne 3
    $days	\h'|2i'# a simple string variable
    $days[28]	\h'|2i'# 29th element of array @days
    $days{'Feb'}\h'|2i'# one value from an associative array

but entire arrays are denoted by \*(L'@\*(R':

    @days	\h'|2i'# ($days[0], $days[1],\|.\|.\|. $days[n])

.fi
.PP
Any of these four constructs may be assigned to (in compiler lingo, may serve
as an lvalue).
(Additionally, you may find the length of array @days by evaluating
\*(L"$#days\*(R", as in
.IR csh .
[Actually, it's not the length of the array, it's the subscript of the last element, since there is (ordinarily) a 0th element.])
.PP
Every data type has its own namespace.
You can, without fear of conflict, use the same name for a string variable,
an array, an associative array, a filehandle, a subroutine name, and/or
a label.
Since variable and array references always start with \*(L'$\*(R'
or \*(L'@\*(R', the \*(L"reserved\*(R" words aren't in fact reserved
with respect to variable names.
(They ARE reserved with respect to labels and filehandles, however, which
don't have an initial special character.)
Case IS significant\*(--\*(L"FOO\*(R", \*(L"Foo\*(R" and \*(L"foo\*(R" are all
different names.
Names which start with a letter may also contain digits and underscores.
Names which do not start with a letter are limited to one character,
e.g. \*(L"$%\*(R" or \*(L"$$\*(R".
(Many one character names have a predefined significance to
.I perl.
More later.)
.PP
String literals are delimited by either single or double quotes.
They work much like shell quotes:
double-quoted string literals are subject to backslash and variable
substitution; single-quoted strings are not.
The usual backslash rules apply for making characters such as newline, tab, etc.
You can also embed newlines directly in your strings, i.e. they can end on
a different line than they begin.
This is nice, but if you forget your trailing quote, the error will not be
reported until perl finds another line containing the quote character, which
may be much further on in the script.
Variable substitution inside strings is limited (currently) to simple string variables.
The following code segment prints out \*(L"The price is $100.\*(R"
.nf

.ne 2
    $Price = '$100';\h'|3.5i'# not interpreted
    print "The price is $Price.\e\|n";\h'|3.5i'# interpreted

.fi
Note that you can put curly brackets around the identifier to delimit it
from following alphanumerics.
.PP
Array literals are denoted by separating individual values by commas, and
enclosing the list in parentheses.
In a context not requiring an array value, the value of the array literal
is the value of the final element, as in the C comma operator.
For example,
.nf

.ne 4
    @foo = ('cc', '\-E', $bar);

assigns the entire array value to array foo, but

    $foo = ('cc', '\-E', $bar);

.fi
assigns the value of variable bar to variable foo.
Array lists may be assigned to if and only if each element of the list
is an lvalue:
.nf

    ($a, $b, $c) = (1, 2, 3);

    ($map{'red'}, $map{'blue'}, $map{'green'}) = (0x00f, 0x0f0, 0xf00);

.fi
.PP
Numeric literals are specified in any of the usual floating point or
integer formats.
.PP
There are several other pseudo-literals that you should know about.
If a string is enclosed by backticks (grave accents), it is interpreted as
a command, and the output of that command is the value of the pseudo-literal,
just like in any of the standard shells.
The command is executed each time the pseudo-literal is evaluated.
Unlike in \f2csh\f1, no interpretation is done on the
data\*(--newlines remain newlines.
The status value of the command is returned in $?.
.PP
Evaluating a filehandle in angle brackets yields the next line
from that file (newline included, so it's never false until EOF).
Ordinarily you must assign that value to a variable,
but there is one situation where in which an automatic assignment happens.
If (and only if) the input symbol is the only thing inside the conditional of a
.I while
loop, the value is
automatically assigned to the variable \*(L"$_\*(R".
(This may seem like an odd thing to you, but you'll use the construct
in almost every
.I perl
script you write.)
Anyway, the following lines are equivalent to each other:
.nf

.ne 3
    while ($_ = <stdin>) {
    while (<stdin>) {
    for (\|;\|<stdin>;\|) {

.fi
The filehandles
.IR stdin ,
.I stdout
and
.I stderr
are predefined.
Additional filehandles may be created with the
.I open
function.
.PP
The null filehandle <> is special and can be used to emulate the behavior of
\fIsed\fR and \fIawk\fR.
Input from <> comes either from standard input, or from each file listed on
the command line.
Here's how it works: the first time <> is evaluated, the ARGV array is checked,
and if it is null, $ARGV[0] is set to '-', which when opened gives you standard
input.
The ARGV array is then processed as a list of filenames.
The loop
.nf

.ne 3
	while (<>) {
		.\|.\|.			# code for each line
	}

.ne 10
is equivalent to

	unshift(@ARGV, '\-') \|if \|$#ARGV < $[;
	while ($ARGV = shift) {
		open(ARGV, $ARGV);
		while (<ARGV>) {
			.\|.\|.		# code for each line
		}
	}

.fi
except that it isn't as cumbersome to say.
It really does shift array ARGV and put the current filename into
variable ARGV.
It also uses filehandle ARGV internally.
You can modify @ARGV before the first <> as long as you leave the first
filename at the beginning of the array.
Line numbers ($.) continue as if the input was one big happy file.
.PP
.ne 5
If you want to set @ARGV to your own list of files, go right ahead.
If you want to pass switches into your script, you can
put a loop on the front like this:
.nf

.ne 10
	while ($_ = $ARGV[0], /\|^\-/\|) {
		shift;
	    last if /\|^\-\|\-$\|/\|;
		/\|^\-D\|(.*\|)/ \|&& \|($debug = $1);
		/\|^\-v\|/ \|&& \|$verbose++;
		.\|.\|.		# other switches
	}
	while (<>) {
		.\|.\|.		# code for each line
	}

.fi
The <> symbol will return FALSE only once.
If you call it again after this it will assume you are processing another
@ARGV list, and if you haven't set @ARGV, will input from stdin.
.Sh "Syntax"
.PP
A
.I perl
script consists of a sequence of declarations and commands.
The only things that need to be declared in
.I perl
are report formats and subroutines.
See the sections below for more information on those declarations.
All objects are assumed to start with a null or 0 value.
The sequence of commands is executed just once, unlike in
.I sed
and
.I awk
scripts, where the sequence of commands is executed for each input line.
While this means that you must explicitly loop over the lines of your input file
(or files), it also means you have much more control over which files and which
lines you look at.
(Actually, I'm lying\*(--it is possible to do an implicit loop with either the
.B \-n
or
.B \-p
switch.)
.PP
A declaration can be put anywhere a command can, but has no effect on the
execution of the primary sequence of commands.
Typically all the declarations are put at the beginning or the end of the script.
.PP
.I Perl
is, for the most part, a free-form language.
(The only exception to this is format declarations, for fairly obvious reasons.)
Comments are indicated by the # character, and extend to the end of the line.
If you attempt to use /* */ C comments, it will be interpreted either as
division or pattern matching, depending on the context.
So don't do that.
.Sh "Compound statements"
In
.IR perl ,
a sequence of commands may be treated as one command by enclosing it
in curly brackets.
We will call this a BLOCK.
.PP
The following compound commands may be used to control flow:
.nf

.ne 4
	if (EXPR) BLOCK
	if (EXPR) BLOCK else BLOCK
	if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK
	LABEL while (EXPR) BLOCK
	LABEL while (EXPR) BLOCK continue BLOCK
	LABEL for (EXPR; EXPR; EXPR) BLOCK
	LABEL BLOCK continue BLOCK

.fi
Note that, unlike C and Pascal, these are defined in terms of BLOCKs, not
statements.
This means that the curly brackets are \fIrequired\fR\*(--no dangling statements allowed.
If you want to write conditionals without curly brackets there are several
other ways to do it.
The following all do the same thing:
.nf

.ne 5
    if (!open(foo)) { die "Can't open $foo"; }
    die "Can't open $foo" unless open(foo);
    open(foo) || die "Can't open $foo";	# foo or bust!
    open(foo) ? die "Can't open $foo" : 'hi mom';
			    # a bit exotic, that last one

.fi
.PP
The
.I if
statement is straightforward.
Since BLOCKs are always bounded by curly brackets, there is never any
ambiguity about which
.I if
an
.I else
goes with.
If you use
.I unless
in place of
.IR if ,
the sense of the test is reversed.
.PP
The
.I while
statement executes the block as long as the expression is true
(does not evaluate to the null string or 0).
The LABEL is optional, and if present, consists of an identifier followed by
a colon.
The LABEL identifies the loop for the loop control statements
.IR next ,
.I last
and
.I redo
(see below).
If there is a
.I continue
BLOCK, it is always executed just before
the conditional is about to be evaluated again, similarly to the third part
of a
.I for
loop in C.
Thus it can be used to increment a loop variable, even when the loop has
been continued via the
.I next
statement (similar to the C \*(L"continue\*(R" statement).
.PP
If the word
.I while
is replaced by the word
.IR until ,
the sense of the test is reversed, but the conditional is still tested before
the first iteration.
.PP
In either the
.I if
or the
.I while
statement, you may replace \*(L"(EXPR)\*(R" with a BLOCK, and the conditional
is true if the value of the last command in that block is true.
.PP
The
.I for
loop works exactly like the corresponding
.I while
loop:
.nf

.ne 12
	for ($i = 1; $i < 10; $i++) {
		.\|.\|.
	}

is the same as

	$i = 1;
	while ($i < 10) {
		.\|.\|.
	} continue {
		$i++;
	}
.fi
.PP
The BLOCK by itself (labeled or not) is equivalent to a loop that executes
once.
Thus you can use any of the loop control statements in it to leave or
restart the block.
The
.I continue
block is optional.
This construct is particularly nice for doing case structures.
.nf

.ne 6
	foo: {
		if (/abc/) { $abc = 1; last foo; }
		if (/def/) { $def = 1; last foo; }
		if (/xyz/) { $xyz = 1; last foo; }
		$nothing = 1;
	}

.fi
.Sh "Simple statements"
The only kind of simple statement is an expression evaluated for its side
effects.
Every expression (simple statement) must be terminated with a semicolon.
Note that this is like C, but unlike Pascal (and
.IR awk ).
.PP
Any simple statement may optionally be followed by a
single modifier, just before the terminating semicolon.
The possible modifiers are:
.nf

.ne 4
	if EXPR
	unless EXPR
	while EXPR
	until EXPR

.fi
The
.I if
and
.I unless
modifiers have the expected semantics.
The
.I while
and
.I unless
modifiers also have the expected semantics (conditional evaluated first),
except when applied to a do-BLOCK command,
in which case the block executes once before the conditional is evaluated.
This is so that you can write loops like:
.nf

.ne 4
	do {
		$_ = <stdin>;
		.\|.\|.
	} until $_ \|eq \|".\|\e\|n";

.fi
(See the
.I do
operator below.  Note also that the loop control commands described later will
NOT work in this construct, since modifiers don't take loop labels.
Sorry.)
.Sh "Expressions"
Since
.I perl
expressions work almost exactly like C expressions, only the differences
will be mentioned here.
.PP
Here's what
.I perl
has that C doesn't:
.Ip (\|) 8 3
The null list, used to initialize an array to null.
.Ip . 8
Concatenation of two strings.
.Ip .= 8
The corresponding assignment operator.
.Ip eq 8
String equality (== is numeric equality).
For a mnemonic just think of \*(L"eq\*(R" as a string.
(If you are used to the
.I awk
behavior of using == for either string or numeric equality
based on the current form of the comparands, beware!
You must be explicit here.)
.Ip ne 8
String inequality (!= is numeric inequality).
.Ip lt 8
String less than.
.Ip gt 8
String greater than.
.Ip le 8
String less than or equal.
.Ip ge 8
String greater than or equal.
.Ip =~ 8 2
Certain operations search or modify the string \*(L"$_\*(R" by default.
This operator makes that kind of operation work on some other string.
The right argument is a search pattern, substitution, or translation.
The left argument is what is supposed to be searched, substituted, or
translated instead of the default \*(L"$_\*(R".
The return value indicates the success of the operation.
(If the right argument is an expression other than a search pattern,
substitution, or translation, it is interpreted as a search pattern
at run time.
This is less efficient than an explicit search, since the pattern must
be compiled every time the expression is evaluated.)
The precedence of this operator is lower than unary minus and autoincrement/decrement, but higher than everything else.
.Ip !~ 8
Just like =~ except the return value is negated.
.Ip x 8
The repetition operator.
Returns a string consisting of the left operand repeated the
number of times specified by the right operand.
.nf

	print '-' x 80;		# print row of dashes
	print '-' x80;		# illegal, x80 is identifier

	print "\et" x ($tab/8), ' ' x ($tab%8);	# tab over

.fi
.Ip x= 8
The corresponding assignment operator.
.Ip .. 8
The range operator, which is bistable.
It is false as long as its left argument is false.
Once the left argument is true, it stays true until the right argument is true,
AFTER which it becomes false again.
(It doesn't become false till the next time it's evaluated.
It can become false on the same evaluation it became true, but it still returns
true once.)
The .. operator is primarily intended for doing line number ranges after
the fashion of \fIsed\fR or \fIawk\fR.
The precedence is a little lower than || and &&.
The value returned is either the null string for false, or a sequence number
(beginning with 1) for true.
The sequence number is reset for each range encountered.
The final sequence number in a range has the string 'E0' appended to it, which
doesn't affect its numeric value, but gives you something to search for if you
want to exclude the endpoint.
You can exclude the beginning point by waiting for the sequence number to be
greater than 1.
If either argument to .. is static, that argument is implicitly compared to
the $. variable, the current line number.
Examples:
.nf

.ne 5
    if (101 .. 200) { print; }	# print 2nd hundred lines

    next line if (1 .. /^$/);	# skip header lines

    s/^/> / if (/^$/ .. eof());	# quote body

.fi
.Ip -x 8
A file test.
This unary operator takes one argument, a filename, and tests the file
to see if something is true about it.
It returns 1 for true and '' for false.
Precedence is higher than logical and relational operators, but lower than
arithmetic operators.
The operator may be any of:
.nf
	-r	File is readable by effective uid.
	-w	File is writeable by effective uid.
	-x	File is executable by effective uid.
	-o	File is owned by effective uid.
	-R	File is readable by real uid.
	-W	File is writeable by real uid.
	-X	File is executable by real uid.
	-O	File is owned by real uid.
	-e	File exists.
	-z	File has zero size.
	-s	File has non-zero size.
	-f	File is a plain file.
	-d	File is a directory.
	-l	File is a symbolic link.

.ne 7
Example:
	
	while (<>) {
		chop;
		next unless -f $_;	# ignore specials
		...
	}

.fi
Note that -s/a/b/ does not do a negated substitution.
.PP
Here is what C has that
.I perl
doesn't:
.Ip "unary &" 12
Address-of operator.
.Ip "unary *" 12
Dereference-address operator.
.PP
Like C,
.I perl
does a certain amount of expression evaluation at compile time, whenever
it determines that all of the arguments to an operator are static and have
no side effects.
In particular, string concatenation happens at compile time between literals that don't do variable substitution.
Backslash interpretation also happens at compile time.
You can say
.nf

.ne 2
	'Now is the time for all' . "\|\e\|n" .
	'good men to come to.'

.fi
and this all reduces to one string internally.
.PP
Along with the literals and variables mentioned earlier,
the following operations can serve as terms in an expression:
.Ip "/PATTERN/i" 8 4
Searches a string for a pattern, and returns true (1) or false ('').
If no string is specified via the =~ or !~ operator,
the $_ string is searched.
(The string specified with =~ need not be an lvalue\*(--it may be the result of an expression evaluation, but remember the =~ binds rather tightly.)
See also the section on regular expressions.
.Sp
If you prepend an `m' you can use any pair of characters as delimiters.
This is particularly useful for matching Unix path names that contain `/'.
If the final delimiter is followed by the optional letter `i', the matching is
done in a case-insensitive manner.
.Sp
Examples:
.nf

.ne 4
    open(tty, '/dev/tty');
    <tty> \|=~ \|/\|^y\|/i \|&& \|do foo(\|);	# do foo if desired

    if (/Version: \|*\|([0-9.]*\|)\|/\|) { $version = $1; }

    next if m#^/usr/spool/uucp#;

.fi
.Ip "?PATTERN?" 8 4
This is just like the /pattern/ search, except that it matches only once between
calls to the
.I reset
operator.
This is a useful optimization when you only want to see the first occurence of
something in each of a set of files, for instance.
.Ip "chdir EXPR" 8 2
Changes the working directory to EXPR, if possible.
Returns 1 upon success, 0 otherwise.
See example under die().
.Ip "chmod LIST" 8 2
Changes the permissions of a list of files.
The first element of the list must be the numerical mode.
LIST may be an array, in which case you may wish to use the unshift()
command to put the mode on the front of the array.
Returns the number of files successfully changed.
Note: in order to use the value you must put the whole thing in parentheses.
.nf

	$cnt = (chmod 0755,'foo','bar');

.fi
.Ip "chop(VARIABLE)" 8 5
.Ip "chop" 8
Chops off the last character of a string and returns it.
It's used primarily to remove the newline from the end of an input record,
but is much more efficient than s/\en// because it neither scans nor copies
the string.
If VARIABLE is omitted, chops $_.
Example:
.nf

.ne 5
	while (<>) {
		chop;	# avoid \en on last field
		@array = split(/:/);
		.\|.\|.
	}

.fi
.Ip "chown LIST" 8 2
Changes the owner (and group) of a list of files.
LIST may be an array.
The first two elements of the list must be the NUMERICAL uid and gid, in that order.
Returns the number of files successfully changed.
Note: in order to use the value you must put the whole thing in parentheses.
.nf

	$cnt = (chown $uid,$gid,'foo');

.fi
.ne 18
Here's an example of looking up non-numeric uids:
.nf

	print "User: ";
	$user = <stdin>;
	chop($user);
	open(pass,'/etc/passwd') || die "Can't open passwd";
	while (<pass>) {
		($login,$pass,$uid,$gid) = split(/:/);
		$uid{$login} = $uid;
		$gid{$login} = $gid;
	}
	@ary = ('foo','bar','bie','doll');
	if ($uid{$user} eq '') {
		die "$user not in passwd file";
	}
	else {
		unshift(@ary,$uid{$user},$gid{$user});
		chown @ary;
	}

.fi
.Ip "close(FILEHANDLE)" 8 5
.Ip "close FILEHANDLE" 8
Closes the file or pipe associated with the file handle.
You don't have to close FILEHANDLE if you are immediately going to
do another open on it, since open will close it for you.
(See
.IR open .)
However, an explicit close on an input file resets the line counter ($.), while
the implicit close done by
.I open
does not.
Also, closing a pipe will wait for the process executing on the pipe to complete,
in case you want to look at the output of the pipe afterwards.
Example:
.nf

.ne 4
	open(output,'|sort >foo');	# pipe to sort
	...	# print stuff to output
	close(output);		# wait for sort to finish
	open(input,'foo');	# get sort's results

.fi
.Ip "crypt(PLAINTEXT,SALT)" 8 6
Encrypts a string exactly like the crypt() function in the C library.
Useful for checking the password file for lousy passwords.
Only the guys wearing white hats should do this.
.Ip "die EXPR" 8 6
Prints the value of EXPR to stderr and exits with a non-zero status.
Equivalent examples:
.nf

.ne 3
	die "Can't cd to spool." unless chdir '/usr/spool/news';

	(chdir '/usr/spool/news') || die "Can't cd to spool." 

.fi
Note that the parens are necessary above due to precedence.
See also
.IR exit .
.Ip "do BLOCK" 8 4
Returns the value of the last command in the sequence of commands indicated
by BLOCK.
When modified by a loop modifier, executes the BLOCK once before testing the
loop condition.
(On other statements the loop modifiers test the conditional first.)
.Ip "do SUBROUTINE (LIST)" 8 3
Executes a SUBROUTINE declared by a
.I sub
declaration, and returns the value
of the last expression evaluated in SUBROUTINE.
(See the section on subroutines later on.)
.Ip "each(ASSOC_ARRAY)" 8 6
Returns a 2 element array consisting of the key and value for the next
value of an associative array, so that you can iterate over it.
Entries are returned in an apparently random order.
When the array is entirely read, a null array is returned (which when
assigned produces a FALSE (0) value).
The next call to each() after that will start iterating again.
The iterator can be reset only by reading all the elements from the array.
You should not modify the array while iterating over it.
The following prints out your environment like the printenv program, only
in a different order:
.nf

.ne 3
	while (($key,$value) = each(ENV)) {
		print "$key=$value\en";
	}

.fi
See also keys() and values().
.Ip "eof(FILEHANDLE)" 8 8
.Ip "eof" 8
Returns 1 if the next read on FILEHANDLE will return end of file, or if
FILEHANDLE is not open.
If (FILEHANDLE) is omitted, the eof status is returned for the last file read.
The null filehandle 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.
Example:
.nf

.ne 7
	# insert dashes just before last line
	while (<>) {
		if (eof()) {
			print "--------------\en";
		}
		print;
	}

.fi
.Ip "eval EXPR" 8 6
EXPR is parsed and executed as if it were a little perl program.
It is executed in the context of the current perl program, so that
any variable settings, subroutine or format definitions remain afterwards.
The value returned is the value of the last expression evaluated, just
as with subroutines.
If there is a syntax error or runtime error, a null string is returned by
eval, and $@ is set to the error message.
If there was no error, $@ is null.
If EXPR is omitted, evaluates $_.
.Ip "exec LIST" 8 6
If there is more than one argument in LIST,
calls execvp() with the arguments in LIST.
If there is only one 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) do not flush your output buffer, so you may need to
set $| to avoid lost output.
.Ip "exit EXPR" 8 6
Evaluates EXPR and exits immediately with that value.
Example:
.nf

.ne 2
	$ans = <stdin>;
	exit 0 \|if \|$ans \|=~ \|/\|^[Xx]\|/\|;

.fi
See also
.IR die .
.Ip "exp(EXPR)" 8 3
Returns e to the power of EXPR.
.Ip "fork" 8 4
Does a fork() call.
Returns the child pid to the parent process and 0 to the child process.
Note: unflushed buffers remain unflushed in both processes, which means
you may need to set $| to avoid duplicate output.
.Ip "gmtime(EXPR)" 8 4
Converts a time as returned by the time function to a 9-element array with
the time analyzed for the Greenwich timezone.
Typically used as follows:
.nf

.ne 3
    ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)
       = gmtime(time);

.fi
All array elements are numeric.
''' End of part 1
''' Beginning of part 2
''' $Header: perl.man.2,v 1.0.1.8 88/03/04 19:11:44 root Exp $
'''
''' $Log:	perl.man.2,v $
''' Revision 1.0.1.8  88/03/04  19:11:44  root
''' patch28: documented killing of process groups
''' 
''' Revision 1.0.1.7  88/03/02  12:36:57  root
''' patch24: documented symlink()
''' 
''' Revision 1.0.1.6  88/02/25  11:44:09  root
''' patch23: two typos and a clarification.
''' 
''' Revision 1.0.1.5  88/02/06  00:22:26  root
''' patch21: documented s/foo/bar/i.
''' 
''' Revision 1.0.1.4  88/02/04  17:48:31  root
''' patch20: documented return values of system better.
''' 
''' Revision 1.0.1.3  88/02/01  17:33:03  root
''' patch12: documented split more adequately.
''' 
''' Revision 1.0.1.2  88/01/30  17:04:28  root
''' patch 11: random cleanup
''' 
''' Revision 1.0.1.1  88/01/28  10:25:11  root
''' patch8: added $@ variable.
''' 
''' Revision 1.0  87/12/18  16:18:41  root
''' Initial revision
''' 
'''
.Ip "goto LABEL" 8 6
Finds the statement labeled with LABEL and resumes execution there.
Currently you may only go to statements in the main body of the program
that are not nested inside a do {} construct.
This statement is not implemented very efficiently, and is here only to make
the sed-to-perl translator easier.
Use at your own risk.
.Ip "hex(EXPR)" 8 2
Returns the decimal value of EXPR interpreted as an hex string.
(To interpret strings that might start with 0 or 0x see oct().)
.Ip "index(STR,SUBSTR)" 8 4
Returns the position of SUBSTR in STR, based at 0, or whatever you've
set the $[ variable to.
If the substring is not found, returns one less than the base, ordinarily -1.
.Ip "int(EXPR)" 8 3
Returns the integer portion of EXPR.
.Ip "join(EXPR,LIST)" 8 8
.Ip "join(EXPR,ARRAY)" 8
Joins the separate strings of LIST or ARRAY into a single string with fields
separated by the value of EXPR, and returns the string.
Example:
.nf
    
    $_ = join(\|':', $login,$passwd,$uid,$gid,$gcos,$home,$shell);

.fi
See
.IR split .
.Ip "keys(ASSOC_ARRAY)" 8 6
Returns a normal array consisting of all the keys of the named associative
array.
The keys are returned in an apparently random order, but it is the same order
as either the values() or each() function produces (given that the associative array
has not been modified).
Here is yet another way to print your environment:
.nf

.ne 5
	@keys = keys(ENV);
	@values = values(ENV);
	while ($#keys >= 0) {
		print pop(keys),'=',pop(values),"\en";
	}

.fi
.Ip "kill LIST" 8 2
Sends a signal to a list of processes.
The first element of the list must be the (numerical) signal to send.
LIST may be an array, in which case you may wish to use the unshift
command to put the signal on the front of the array.
Returns the number of processes successfully signaled.
Note: in order to use the value you must put the whole thing in parentheses:
.nf

	$cnt = (kill 9,$child1,$child2);

.fi
If the signal is negative, kills process groups instead of processes.
(On System V, a negative \fIprocess\fR number will also kill process groups,
but that's not portable.)
.Ip "last LABEL" 8 8
.Ip "last" 8
The
.I last
command is like the
.I break
statement in C (as used in loops); it immediately exits the loop in question.
If the LABEL is omitted, the command refers to the innermost enclosing loop.
The
.I continue
block, if any, is not executed:
.nf

.ne 4
	line: while (<stdin>) {
		last line if /\|^$/;	# exit when done with header
		.\|.\|.
	}

.fi
.Ip "localtime(EXPR)" 8 4
Converts a time as returned by the time function to a 9-element array with
the time analyzed for the local timezone.
Typically used as follows:
.nf

.ne 3
    ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)
       = localtime(time);

.fi
All array elements are numeric.
.Ip "log(EXPR)" 8 3
Returns logarithm (base e) of EXPR.
.Ip "next LABEL" 8 8
.Ip "next" 8
The
.I next
command is like the
.I continue
statement in C; it starts the next iteration of the loop:
.nf

.ne 4
	line: while (<stdin>) {
		next line if /\|^#/;	# discard comments
		.\|.\|.
	}

.fi
Note that if there were a
.I 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.
.Ip "length(EXPR)" 8 2
Returns the length in characters of the value of EXPR.
.Ip "link(OLDFILE,NEWFILE)" 8 2
Creates a new filename linked to the old filename.
Returns 1 for success, 0 otherwise.
.Ip "oct(EXPR)" 8 2
Returns the decimal value of EXPR interpreted as an octal string.
(If EXPR happens to start off with 0x, interprets it as a hex string instead.)
The following will handle decimal, octal and hex in the standard notation:
.nf

	$val = oct($val) if $val =~ /^0/;

.fi
.Ip "open(FILEHANDLE,EXPR)" 8 8
.Ip "open(FILEHANDLE)" 8
.Ip "open FILEHANDLE" 8
Opens the file whose filename is given by EXPR, and associates it with
FILEHANDLE.
If EXPR is omitted, the string variable of the same name as the FILEHANDLE
contains the filename.
If the filename begins with \*(L">\*(R", the file is opened for output.
If the filename begins with \*(L">>\*(R", the file is opened for appending.
If the filename begins with \*(L"|\*(R", the filename is interpreted
as a command to which output is to be piped, and if the filename ends
with a \*(L"|\*(R", the filename is interpreted as command which pipes
input to us.
(You may not have a command that pipes both in and out.)
Opening '\-' opens stdin and opening '>\-' opens stdout.
Open returns 1 upon success, '' otherwise.
Examples:
.nf
    
.ne 3
    $article = 100;
    open article || die "Can't find article $article";
    while (<article>) {\|.\|.\|.

    open(log, '>>/usr/spool/news/twitlog'\|);

    open(article, "caeser <$article |"\|);		# decrypt article

    open(extract, "|sort >/tmp/Tmp$$"\|);		# $$ is our process#

.fi
.Ip "ord(EXPR)" 8 3
Returns the ascii value of the first character of EXPR.
.Ip "pop ARRAY" 8 6
.Ip "pop(ARRAY)" 8
Pops and returns the last value of the array, shortening the array by 1.
''' $tmp = $ARRAY[$#ARRAY--]
.Ip "print FILEHANDLE LIST" 8 9
.Ip "print LIST" 8
.Ip "print" 8
Prints a string or comma-separated list of strings.
If FILEHANDLE is omitted, prints by default to standard output (or to the
last selected output channel\*(--see select()).
If LIST is also omitted, prints $_ to stdout.
LIST may also be an array value.
To set the default output channel to something other than stdout use the select operation.
.Ip "printf FILEHANDLE LIST" 8 9
.Ip "printf LIST" 8
Equivalent to a "print FILEHANDLE sprintf(LIST)".
.Ip "push(ARRAY,EXPR)" 8 7
Treats ARRAY (@ is optional) as a stack, and pushes the value of EXPR
onto the end of ARRAY.
The length of ARRAY increases by 1.
Has the same effect as
.nf

    $ARRAY[$#ARRAY+1] = EXPR;

.fi
but is more efficient.
.Ip "redo LABEL" 8 8
.Ip "redo" 8
The
.I redo
command restarts the loop block without evaluating the conditional again.
The
.I continue
block, if any, is not executed.
If the LABEL is omitted, the command refers to the innermost enclosing loop.
This command is normally used by programs that want to lie to themselves
about what was just input:
.nf

.ne 16
	# 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;
	}

.fi
.Ip "rename(OLDNAME,NEWNAME)" 8 2
Changes the name of a file.
Returns 1 for success, 0 otherwise.
.Ip "reset EXPR" 8 3
Generally used in a
.I continue
block at the end of a loop to clear variables and reset ?? searches
so that they work again.
The expression is interpreted as a list of single characters (hyphens allowed
for ranges).
All string variables beginning with one of those letters are set to the null
string.
If the expression is omitted, one-match searches (?pattern?) are reset to
match again.
Always returns 1.
Examples:
.nf

.ne 3
    reset 'X';	\h'|2i'# reset all X variables
    reset 'a-z';\h'|2i'# reset lower case variables
    reset;	\h'|2i'# just reset ?? searches

.fi
.Ip "s/PATTERN/REPLACEMENT/gi" 8 3
Searches a string for a pattern, and if found, replaces that pattern with the
replacement text and returns the number of substitutions made.
Otherwise it returns false (0).
The \*(L"g\*(R" is optional, and if present, indicates that all occurences
of the pattern are to be replaced.
The \*(L"i\*(R" is also optional, and if present, indicates that matching
is to be done in a case-insensitive manner.
Any delimiter may replace the slashes; if single quotes are used, no
interpretation is done on the replacement string.
If no string is specified via the =~ or !~ operator,
the $_ string is searched and modified.
(The string specified with =~ must be a string variable or array element,
i.e. an lvalue.)
If the pattern contains a $ that looks like a variable rather than an
end-of-string test, the variable will be interpolated into the pattern at
run-time.
See also the section on regular expressions.
Examples:
.nf

    s/\|\e\|bgreen\e\|b/mauve/g;		# don't change wintergreen

    $path \|=~ \|s|\|/usr/bin|\|/usr/local/bin|;

    s/Login: $foo/Login: $bar/; # run-time pattern

    s/\|([^ \|]*\|) *\|([^ \|]*\|)\|/\|$2 $1/;	# reverse 1st two fields

.fi
(Note the use of $ instead of \|\e\| in the last example.  See section
on regular expressions.)
.Ip "seek(FILEHANDLE,POSITION,WHENCE)" 8 3
Randomly positions the file pointer for FILEHANDLE, just like the fseek()
call of stdio.
Returns 1 upon success, 0 otherwise.
.Ip "select(FILEHANDLE)" 8 3
Sets the current default filehandle for output.
This has two effects: first, a
.I write
or a
.I print
without a filehandle will default to this FILEHANDLE.
Second, references to variables related to output will refer to this output
channel.
For example, if you have to set the top of form format for more than
one output channel, you might do the following:
.nf

.ne 4
    select(report1);
    $^ = 'report1_top';
    select(report2);
    $^ = 'report2_top';

.fi
Select happens to return TRUE if the file is currently open and FALSE otherwise,
but this has no effect on its operation.
.Ip "shift(ARRAY)" 8 6
.Ip "shift ARRAY" 8
.Ip "shift" 8
Shifts the first value of the array off and returns it,
shortening the array by 1 and moving everything down.
If ARRAY is omitted, shifts the ARGV array.
See also unshift(), push() and pop().
Shift() and unshift() do the same thing to the left end of an array that push()
and pop() do to the right end.
.Ip "sleep EXPR" 8 6
.Ip "sleep" 8
Causes the script to sleep for EXPR seconds, or forever if no EXPR.
May be interrupted by sending the process a SIGALARM.
Returns the number of seconds actually slept.
.Ip "split(/PATTERN/,EXPR)" 8 8
.Ip "split(/PATTERN/)" 8
.Ip "split" 8
Splits a string into an array of strings, and returns it.
If EXPR is omitted, splits the $_ string.
If PATTERN is also omitted, splits on whitespace (/[\ \et\en]+/).
Anything matching PATTERN is taken to be a delimiter separating the fields.
(Note that the delimiter may be longer than one character.)
Trailing null fields are stripped, which potential users of pop() would
do well to remember.
A pattern matching the null string (not to be confused with a null pattern)
will split the value of EXPR into separate characters at each point it
matches that way.
For example:
.nf

	print join(':',split(/ */,'hi there'));

.fi
produces the output 'h:i:t:h:e:r:e'.

The pattern /PATTERN/ may be replaced with an expression to specify patterns
that vary at runtime.
As a special case, specifying a space ('\ ') will split on white space
just as split with no arguments does, but leading white space does NOT
produce a null first field.
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.
.sp
Example:
.nf

.ne 5
	open(passwd, '/etc/passwd');
	while (<passwd>) {
.ie t \{\
		($login, $passwd, $uid, $gid, $gcos, $home, $shell) = split(\|/\|:\|/\|);
'br\}
.el \{\
		($login, $passwd, $uid, $gid, $gcos, $home, $shell)
			= split(\|/\|:\|/\|);
'br\}
		.\|.\|.
	}

.fi
(Note that $shell above will still have a newline on it.  See chop().)
See also
.IR join .
.Ip "sprintf(FORMAT,LIST)" 8 4
Returns a string formatted by the usual printf conventions.
The * character is not supported.
.Ip "sqrt(EXPR)" 8 3
Return the square root of EXPR.
.Ip "stat(FILEHANDLE)" 8 6
.Ip "stat(EXPR)" 8
Returns a 13-element array giving the statistics for a file, either the file
opened via FILEHANDLE, or named by EXPR.
Typically used as follows:
.nf

.ne 3
    ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
       $atime,$mtime,$ctime,$blksize,$blocks)
           = stat($filename);

.fi
.Ip "substr(EXPR,OFFSET,LEN)" 8 2
Extracts a substring out of EXPR and returns it.
First character is at offset 0, or whatever you've set $[ to.
.Ip "system LIST" 8 6
Does exactly the same thing as \*(L"exec LIST\*(R" except that a fork
is done first, and the parent process waits for the child process to complete.
Note that argument processing varies depending on the number of arguments.
The return value is the exit status of the program as returned by the wait()
call.
To get the actual exit value divide by 256.
See also exec.
.Ip "symlink(OLDFILE,NEWFILE)" 8 2
Creates a new filename symbolically linked to the old filename.
Returns 1 for success, 0 otherwise.
On systems that don't support symbolic links, produces a fatal error.
.Ip "tell(FILEHANDLE)" 8 6
.Ip "tell" 8
Returns the current file position for FILEHANDLE.
If FILEHANDLE is omitted, assumes the file last read.
.Ip "time" 8 4
Returns the number of seconds since January 1, 1970.
Suitable for feeding to gmtime() and localtime().
.Ip "times" 8 4
Returns a four-element array giving the user and system times, in seconds, for this
process and the children of this process.
.sp
    ($user,$system,$cuser,$csystem) = times;
.sp
.Ip "tr/SEARCHLIST/REPLACEMENTLIST/" 8 5
.Ip "y/SEARCHLIST/REPLACEMENTLIST/" 8
Translates all occurences of the characters found in the search list with
the corresponding character in the replacement list.
It returns the number of characters replaced.
If no string is specified via the =~ or !~ operator,
the $_ string is translated.
(The string specified with =~ must be a string variable or array element,
i.e. an lvalue.)
For
.I sed
devotees,
.I y
is provided as a synonym for
.IR tr .
Examples:
.nf

    $ARGV[1] \|=~ \|y/A-Z/a-z/;	\h'|3i'# canonicalize to lower case

    $cnt = tr/*/*/;		\h'|3i'# count the stars in $_

.fi
.Ip "umask(EXPR)" 8 3
Sets the umask for the process and returns the old one.
.Ip "unlink LIST" 8 2
Deletes a list of files.
LIST may be an array.
Returns the number of files successfully deleted.
Note: in order to use the value you must put the whole thing in parentheses:
.nf

	$cnt = (unlink 'a','b','c');

.fi
.ne 7
.Ip "unshift(ARRAY,LIST)" 8 4
Does the opposite of a shift.
Prepends list to the front of the array, and returns the number of elements
in the new array.
.nf

	unshift(ARGV,'-e') unless $ARGV[0] =~ /^-/;

.fi
.Ip "values(ASSOC_ARRAY)" 8 6
Returns a normal array consisting of all the values of the named associative
array.
The values are returned in an apparently random order, but it is the same order
as either the keys() or each() function produces (given that the associative array
has not been modified).
See also keys() and each().
.Ip "write(FILEHANDLE)" 8 6
.Ip "write(EXPR)" 8
.Ip "write(\|)" 8
Writes a formatted record (possibly multi-line) to the specified file,
using the format associated with that file.
By default the format for a file is the one having the same name is the
filehandle, but the format for the current output channel (see
.IR select )
may be set explicitly
by assigning the name of the format to the $~ variable.
.sp
Top of form processing is handled automatically:
if there is insufficient room on the current page for the formatted 
record, the page is advanced, 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 \*(L"top\*(R", but it
may be set to the
format of your choice by assigning the name to the $^ variable.
.sp
If FILEHANDLE is unspecified, output goes to the current default output channel,
which starts out as stdout but may be changed by the
.I 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 section on formats later on.
.Sh "Subroutines"
A subroutine may be declared as follows:
.nf

    sub NAME BLOCK

.fi
.PP
Any arguments passed to the routine come in as array @_,
that is ($_[0], $_[1], .\|.\|.).
The return value of the subroutine is the value of the last expression
evaluated.
There are no local variables\*(--everything is a global variable.
.PP
A subroutine is called using the
.I do
operator.
(CAVEAT: For efficiency reasons recursive subroutine calls are not currently
supported.
This restriction may go away in the future.  Then again, it may not.)
.nf

.ne 12
Example:

	sub MAX {
		$max = pop(@_);
		while ($foo = pop(@_)) {
			$max = $foo \|if \|$max < $foo;
		}
		$max;
	}

	.\|.\|.
	$bestday = do MAX($mon,$tue,$wed,$thu,$fri);

.ne 21
Example:

	# get a line, combining continuation lines
	#  that start with whitespace
	sub get_line {
		$thisline = $lookahead;
		line: while ($lookahead = <stdin>) {
			if ($lookahead \|=~ \|/\|^[ \^\e\|t]\|/\|) {
				$thisline \|.= \|$lookahead;
			}
			else {
				last line;
			}
		}
		$thisline;
	}

	$lookahead = <stdin>;	# get first line
	while ($_ = get_line(\|)) {
		.\|.\|.
	}

.fi
.nf
.ne 6
Use array assignment to name your formal arguments:

	sub maybeset {
		($key,$value) = @_;
		$foo{$key} = $value unless $foo{$key};
	}

.fi
.Sh "Regular Expressions"
The patterns used in pattern matching are regular expressions such as
those used by
.IR egrep (1).
In addition, \ew matches an alphanumeric character and \eW a nonalphanumeric.
Word boundaries may be matched by \eb, and non-boundaries by \eB.
The bracketing construct \|(\ .\|.\|.\ \|) may also be used, $<digit>
matches the digit'th substring, where digit can range from 1 to 9.
(You can also use the old standby \e<digit> in search patterns,
but $<digit> also works in replacement patterns and in the block controlled
by the current conditional.)
$+ returns whatever the last bracket match matched.
$& returns the entire matched string.
Up to 10 alternatives may given in a pattern, separated by |, with the
caveat that \|(\ .\|.\|.\ |\ .\|.\|.\ \|) is illegal.
Examples:
.nf
    
	s/\|^\|([^ \|]*\|) \|*([^ \|]*\|)\|/\|$2 $1\|/;	# swap first two words

.ne 5
	if (/\|Time: \|(.\|.\|):\|(.\|.\|):\|(.\|.\|)\|/\|) {
		$hours = $1;
		$minutes = $2;
		$seconds = $3;
	}

.fi
By default, the ^ character matches only the beginning of the string, and
.I perl
does certain optimizations with the assumption that the string contains
only one line.
You may, however, wish to treat a string as a multi-line buffer, such that
the ^ will match after any newline within the string.
At the cost of a little more overhead, you can do this by setting the variable
$* to 1.
Setting it back to 0 makes
.I perl
revert to its old behavior.
.Sh "Formats"
Output record formats for use with the
.I write
operator may declared as follows:
.nf

.ne 3
    format NAME =
    FORMLIST
    .

.fi
If name is omitted, format \*(L"stdout\*(R" is defined.
FORMLIST consists of a sequence of lines, each of which may be of one of three
types:
.Ip 1. 4
A comment.
.Ip 2. 4
A \*(L"picture\*(R" line giving the format for one output line.
.Ip 3. 4
An argument line supplying values to plug into a picture line.
.PP
Picture lines are printed exactly as they look, except for certain fields
that substitute values into the line.
Each picture field starts with either @ or ^.
The @ field (not to be confused with the array marker @) is the normal
case; ^ fields are used
to do rudimentary multi-line text block filling.
The length of the field is supplied by padding out the field
with multiple <, >, or | characters to specify, respectively, left justfication,
right justification, or centering.
If any of the values supplied for these fields contains a newline, only
the text up to the newline is printed.
The special field @* can be used for printing multi-line values.
It should appear by itself on a line.
.PP
The values are specified on the following line, in the same order as
the picture fields.
They must currently be either string variable names or string literals (or
pseudo-literals).
Currently you can separate values with spaces, but commas may be placed
between values to prepare for possible future versions in which full expressions
are allowed as values.
.PP
Picture fields that begin with ^ rather than @ are treated specially.
The value supplied must be a string variable name which contains a text
string.
.I Perl
puts as much text as it can into the field, and then chops off the front
of the string so that the next time the string variable is referenced,
more of the text can be printed.
Normally you would use a sequence of fields in a vertical stack to print
out a block of text.
If you like, you can end the final field with .\|.\|., which will appear in the
output if the text was too long to appear in its entirety.
.PP
Since use of ^ fields can produce variable length records if the text to be
formatted is short, you can suppress blank lines by putting the tilde (~)
character anywhere in the line.
(Normally you should put it in the front if possible.)
The tilde will be translated to a space upon output.
.PP
Examples:
.nf
.lg 0
.cs R 25

.ne 10
# a report on the /etc/passwd file
format top =
\&                        Passwd File
Name                Login    Office   Uid   Gid Home
------------------------------------------------------------------
\&.
format stdout =
@<<<<<<<<<<<<<<<<<< @||||||| @<<<<<<@>>>> @>>>> @<<<<<<<<<<<<<<<<<
$name               $login   $office $uid $gid  $home
\&.

.ne 29
# a report from a bug report form
format top =
\&                        Bug Reports
@<<<<<<<<<<<<<<<<<<<<<<<     @|||         @>>>>>>>>>>>>>>>>>>>>>>>
$system;                      $%;         $date
------------------------------------------------------------------
\&.
format stdout =
Subject: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
\&         $subject
Index: @<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
\&       $index                        $description
Priority: @<<<<<<<<<< Date: @<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
\&          $priority         $date    $description
From: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
\&      $from                          $description
Assigned to: @<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
\&             $programmer             $description
\&~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
\&                                     $description
\&~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
\&                                     $description
\&~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
\&                                     $description
\&~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
\&                                     $description
\&~                                    ^<<<<<<<<<<<<<<<<<<<<<<<...
\&                                     $description
\&.

.cs R
.lg
It is possible to intermix prints with writes on the same output channel,
but you'll have to handle $\- (lines left on the page) yourself.
.fi
.PP
If you are printing lots of fields that are usually blank, you should consider
using the reset operator between records.
Not only is it more efficient, but it can prevent the bug of adding another
field and forgetting to zero it.
.Sh "Predefined Names"
The following names have special meaning to
.IR perl .
I could have used alphabetic symbols for some of these, but I didn't want
to take the chance that someone would say reset "a-zA-Z" and wipe them all
out.
You'll just have to suffer along with these silly symbols.
Most of them have reasonable mnemonics, or analogues in one of the shells.
.Ip $_ 8
The default input and pattern-searching space.
The following pairs are equivalent:
.nf

.ne 2
	while (<>) {\|.\|.\|.	# only equivalent in while!
	while ($_ = <>) {\|.\|.\|.

.ne 2
	/\|^Subject:/
	$_ \|=~ \|/\|^Subject:/

.ne 2
	y/a-z/A-Z/
	$_ =~ y/a-z/A-Z/

.ne 2
	chop
	chop($_)

.fi 
(Mnemonic: underline is understood in certain operations.)
.Ip $. 8
The current input line number of the last file that was read.
Readonly.
(Mnemonic: many programs use . to mean the current line number.)
.Ip $/ 8
The input record separator, newline by default.
Works like awk's RS variable, including treating blank lines as delimiters
if set to the null string.
If set to a value longer than one character, only the first character is used.
(Mnemonic: / is used to delimit line boundaries when quoting poetry.)
.Ip $, 8
The output field separator for the print operator.
Ordinarily the print operator simply prints out the comma separated fields
you specify.
In order to get behavior more like awk, set this variable as you would set
awk's OFS variable to specify what is printed between fields.
(Mnemonic: what is printed when there is a , in your print statement.)
.Ip $\e 8
The output record separator for the print operator.
Ordinarily the print operator simply prints out the comma separated fields
you specify, with no trailing newline or record separator assumed.
In order to get behavior more like awk, set this variable as you would set
awk's ORS variable to specify what is printed at the end of the print.
(Mnemonic: you set $\e instead of adding \en at the end of the print.
Also, it's just like /, but it's what you get \*(L"back\*(R" from perl.)
.Ip $# 8
The output format for printed numbers.
This variable is a half-hearted attempt to emulate awk's OFMT variable.
There are times, however, when awk and perl have differing notions of what
is in fact numeric.
Also, the initial value is %.20g rather than %.6g, so you need to set $#
explicitly to get awk's value.
(Mnemonic: # is the number sign.)
.Ip $% 8
The current page number of the currently selected output channel.
(Mnemonic: % is page number in nroff.)
.Ip $= 8
The current page length (printable lines) of the currently selected output
channel.
Default is 60.
(Mnemonic: = has horizontal lines.)
.Ip $\- 8
The number of lines left on the page of the currently selected output channel.
(Mnemonic: lines_on_page - lines_printed.)
.Ip $~ 8
The name of the current report format for the currently selected output
channel.
(Mnemonic: brother to $^.)
.Ip $^ 8
The name of the current top-of-page format for the currently selected output
channel.
(Mnemonic: points to top of page.)
.Ip $| 8
If set to nonzero, forces a flush after every write or print on the currently
selected output channel.
Default is 0.
Note that stdout will typically be line buffered if output is to the
terminal and block buffered otherwise.
Setting this variable is useful primarily when you are outputting to a pipe,
such as when you are running a perl script under rsh and want to see the
output as it's happening.
(Mnemonic: when you want your pipes to be piping hot.)
.Ip $$ 8
The process number of the
.I perl
running this script.
(Mnemonic: same as shells.)
.Ip $? 8
The status returned by the last backtick (``) command.
(Mnemonic: same as sh and ksh.)
.Ip $+ 8 4
The last bracket matched by the last search pattern.
This is useful if you don't know which of a set of alternative patterns
matched.
For example:
.nf

    /Version: \|(.*\|)|Revision: \|(.*\|)\|/ \|&& \|($rev = $+);

.fi
(Mnemonic: be positive and forward looking.)
.Ip $* 8 2
Set to 1 to do multiline matching within a string, 0 to assume strings contain
a single line.
Default is 0.
(Mnemonic: * matches multiple things.)
.Ip $0 8
Contains the name of the file containing the
.I perl
script being executed.
The value should be copied elsewhere before any pattern matching happens, which
clobbers $0.
(Mnemonic: same as sh and ksh.)
.Ip $<digit> 8
Contains the subpattern from the corresponding set of parentheses in the last
pattern matched, not counting patterns matched in nested blocks that have
been exited already.
(Mnemonic: like \edigit.)
.Ip $[ 8 2
The index of the first element in an array, and of the first character in
a substring.
Default is 0, but you could set it to 1 to make
.I perl
behave more like
.I awk
(or Fortran)
when subscripting and when evaluating the index() and substr() functions.
(Mnemonic: [ begins subscripts.)
.Ip $! 8 2
The current value of errno, with all the usual caveats.
(Mnemonic: What just went bang?)
.Ip $@ 8 2
The error message from the last eval command.
If null, the last eval parsed and executed correctly.
(Mnemonic: Where was the syntax error "at"?)
.Ip @ARGV 8 3
The array ARGV contains the command line arguments intended for the script.
Note that $#ARGV is the generally number of arguments minus one, since
$ARGV[0] is the first argument, NOT the command name.
See $0 for the command name.
.Ip $ENV{expr} 8 2
The associative array ENV contains your current environment.
Setting a value in ENV changes the environment for child processes.
.Ip $SIG{expr} 8 2
The associative array SIG is used to set signal handlers for various signals.
Example:
.nf

.ne 12
	sub handler {	# 1st argument is signal name
		($sig) = @_;
		print "Caught a SIG$sig--shutting down\n";
		close(log);
		exit(0);
	}

	$SIG{'INT'} = 'handler';
	$SIG{'QUIT'} = 'handler';
	...
	$SIG{'INT'} = 'DEFAULT';	# restore default action
	$SIG{'QUIT'} = 'IGNORE';	# ignore SIGQUIT

.fi
.SH ENVIRONMENT
.I Perl
currently uses no environment variables, except to make them available
to the script being executed, and to child processes.
However, scripts running setuid would do well to execute the following lines
before doing anything else, just to keep people honest:
.nf

.ne 3
    $ENV{'PATH'} = '/bin:/usr/bin';    # or whatever you need
    $ENV{'SHELL'} = '/bin/sh' if $ENV{'SHELL'};
    $ENV{'IFS'} = '' if $ENV{'IFS'};

.fi
.SH AUTHOR
Larry Wall <lwall@jpl-devvax.Jpl.Nasa.Gov>
.SH FILES
/tmp/perl\-eXXXXXX	temporary file for
.B \-e
commands.
.SH SEE ALSO
a2p	awk to perl translator
.br
s2p	sed to perl translator
.br
perldb	interactive perl debugger
.SH DIAGNOSTICS
Compilation errors will tell you the line number of the error, with an
indication of the next token or token type that was to be examined.
(In the case of a script passed to
.I perl
via
.B \-e
switches, each
.B \-e
is counted as one line.)
.SH TRAPS
Accustomed awk users should take special note of the following:
.Ip * 4 2
Semicolons are required after all simple statements in perl.  Newline
is not a statement delimiter.
.Ip * 4 2
Curly brackets are required on ifs and whiles.
.Ip * 4 2
Variables begin with $ or @ in perl.
.Ip * 4 2
Arrays index from 0 unless you set $[.
Likewise string positions in substr() and index().
.Ip * 4 2
You have to decide whether your array has numeric or string indices.
.Ip * 4 2
You have to decide whether you want to use string or numeric comparisons.
.Ip * 4 2
Reading an input line does not split it for you.  You get to split it yourself
to an array.
And split has different arguments.
.Ip * 4 2
The current input line is normally in $_, not $0.
It generally does not have the newline stripped.
($0 is initially the name of the program executed, then the last matched
string.)
.Ip * 4 2
The current filename is $ARGV, not $FILENAME.
NR, RS, ORS, OFS, and OFMT have equivalents with other symbols.
FS doesn't have an equivalent, since you have to be explicit about
split statements.
.Ip * 4 2
$<digit> does not refer to fields--it refers to substrings matched by the last
match pattern.
.Ip * 4 2
The print statement does not add field and record separators unless you set
$, and $\e.
.Ip * 4 2
You must open your files before you print to them.
.Ip * 4 2
The range operator is \*(L"..\*(R", not comma.
(The comma operator works as in C.)
.Ip * 4 2
The match operator is \*(L"=~\*(R", not \*(L"~\*(R".
(\*(L"~\*(R" is the one's complement operator.)
.Ip * 4 2
The concatenation operator is \*(L".\*(R", not the null string.
(Using the null string would render \*(L"/pat/ /pat/\*(R" unparseable,
since the third slash would be interpreted as a division operator\*(--the
tokener is in fact slightly context sensitive for operators like /, ?, and <.
And in fact, . itself can be the beginning of a number.)
.Ip * 4 2
The \ennn construct in patterns must be given as [\ennn] to avoid interpretation
as a backreference.
.Ip * 4 2
Next, exit, and continue work differently.
.Ip * 4 2
When in doubt, run the awk construct through a2p and see what it gives you.
.PP
Cerebral C programmers should take note of the following:
.Ip * 4 2
Curly brackets are required on ifs and whiles.
.Ip * 4 2
You should use \*(L"elsif\*(R" rather than \*(L"else if\*(R"
.Ip * 4 2
Break and continue become last and next, respectively.
.Ip * 4 2
There's no switch statement.
.Ip * 4 2
Variables begin with $ or @ in perl.
.Ip * 4 2
Printf does not implement *.
.Ip * 4 2
Comments begin with #, not /*.
.Ip * 4 2
You can't take the address of anything.
.Ip * 4 2
Subroutines are not reentrant.
.Ip * 4 2
ARGV must be capitalized.
.Ip * 4 2
The \*(L"system\*(R" calls link, unlink, rename, etc. return 1 for success, not 0.
.Ip * 4 2
Signal handlers deal with signal names, not numbers.
.PP
Seasoned sed programmers should take note of the following:
.Ip * 4 2
Backreferences in substitutions use $ rather than \e.
.Ip * 4 2
The pattern matching metacharacters (, ), and | do not have backslashes in front.
.SH BUGS
.PP
You can't currently dereference array elements inside a double-quoted string.
You must assign them to a temporary and interpolate that.
.PP
Associative arrays really ought to be first class objects.
.PP
Recursive subroutines are not currently supported, due to the way temporary
values are stored in the syntax tree.
.PP
Arrays ought to be passable to subroutines just as strings are.
.PP
The array literal consisting of one element is currently misinterpreted, i.e.
.nf

	@array = (123);

.fi
doesn't work right.
.PP
.I Perl
actually stands for Pathologically Eclectic Rubbish Lister, but don't tell
anyone I said that.
.rn }` ''
-- 
ron (rminnich@udel.edu)