[comp.sources.misc] v18i026: perl - The perl programming language, Part08/36

lwall@netlabs.com (Larry Wall) (04/16/91)

Submitted-by: Larry Wall <lwall@netlabs.com>
Posting-number: Volume 18, Issue 26
Archive-name: perl/part08

[There are 36 kits for perl version 4.0.]

#! /bin/sh

# Make a new directory for the perl sources, cd to it, and run kits 1
# thru 36 through sh.  When all 36 kits have been run, read README.

echo "This is perl 4.0 kit 8 (of 36).  If kit 8 is complete, the line"
echo '"'"End of kit 8 (of 36)"'" will echo at the end.'
echo ""
export PATH || (echo "You didn't use sh, you clunch." ; kill $$)
mkdir  2>/dev/null
echo Extracting perl.man:AC
sed >perl.man:AC <<'!STUFFY!FUNK!' -e 's/X//'
Xpadding with nulls or spaces as necessary.
X(When unpacking, "A" strips trailing spaces and nulls, but "a" does not.)
XLikewise, the "b" and "B" fields pack a string that many bits long.
XThe "h" and "H" fields pack a string that many nybbles long.
XReal numbers (floats and doubles) are in the native machine format
Xonly; due to the multiplicity of floating formats around, and the lack
Xof a standard \*(L"network\*(R" representation, no facility for
Xinterchange has been made.
XThis means that packed floating point data
Xwritten on one machine may not be readable on another - even if both
Xuse IEEE floating point arithmetic (as the endian-ness of the memory
Xrepresentation is not part of the IEEE spec).
XNote that perl uses
Xdoubles internally for all numeric calculation, and converting from
Xdouble -> float -> double will lose precision (i.e. unpack("f",
Xpack("f", $foo)) will not in general equal $foo).
X.br
XExamples:
X.nf
X
X	$foo = pack("cccc",65,66,67,68);
X	# foo eq "ABCD"
X	$foo = pack("c4",65,66,67,68);
X	# same thing
X
X	$foo = pack("ccxxcc",65,66,67,68);
X	# foo eq "AB\e0\e0CD"
X
X	$foo = pack("s2",1,2);
X	# "\e1\e0\e2\e0" on little-endian
X	# "\e0\e1\e0\e2" on big-endian
X
X	$foo = pack("a4","abcd","x","y","z");
X	# "abcd"
X
X	$foo = pack("aaaa","abcd","x","y","z");
X	# "axyz"
X
X	$foo = pack("a14","abcdefg");
X	# "abcdefg\e0\e0\e0\e0\e0\e0\e0"
X
X	$foo = pack("i9pl", gmtime);
X	# a real struct tm (on my system anyway)
X
X	sub bintodec {
X	    unpack("N", pack("B32", substr("0" x 32 . shift, -32)));
X	}
X.fi
XThe same template may generally also be used in the unpack function.
X.Ip "pipe(READHANDLE,WRITEHANDLE)" 8 3
XOpens a pair of connected pipes like the corresponding system call.
XNote that if you set up a loop of piped processes, deadlock can occur
Xunless you are very careful.
XIn addition, note that perl's pipes use stdio buffering, so you may need
Xto set $| to flush your WRITEHANDLE after each command, depending on
Xthe application.
X[Requires version 3.0 patchlevel 9.]
X.Ip "pop(ARRAY)" 8
X.Ip "pop ARRAY" 8 6
XPops and returns the last value of the array, shortening the array by 1.
XHas the same effect as
X.nf
X
X	$tmp = $ARRAY[$#ARRAY\-\|\-];
X
X.fi
XIf there are no elements in the array, returns the undefined value.
X.Ip "print(FILEHANDLE LIST)" 8 10
X.Ip "print(LIST)" 8
X.Ip "print FILEHANDLE LIST" 8
X.Ip "print LIST" 8
X.Ip "print" 8
XPrints a string or a comma-separated list of strings.
XReturns non-zero if successful.
XFILEHANDLE may be a scalar variable name, in which case the variable contains
Xthe name of the filehandle, thus introducing one level of indirection.
X(NOTE: If FILEHANDLE is a variable and the next token is a term, it may be
Xmisinterpreted as an operator unless you interpose a + or put parens around
Xthe arguments.)
XIf FILEHANDLE is omitted, prints by default to standard output (or to the
Xlast selected output channel\*(--see select()).
XIf LIST is also omitted, prints $_ to
X.IR STDOUT .
XTo set the default output channel to something other than
X.I STDOUT
Xuse the select operation.
XNote that, because print takes a LIST, anything in the LIST is evaluated
Xin an array context, and any subroutine that you call will have one or more
Xof its expressions evaluated in an array context.
XAlso be careful not to follow the print keyword with a left parenthesis
Xunless you want the corresponding right parenthesis to terminate the
Xarguments to the print\*(--interpose a + or put parens around all the arguments.
X.Ip "printf(FILEHANDLE LIST)" 8 10
X.Ip "printf(LIST)" 8
X.Ip "printf FILEHANDLE LIST" 8
X.Ip "printf LIST" 8
XEquivalent to a \*(L"print FILEHANDLE sprintf(LIST)\*(R".
X.Ip "push(ARRAY,LIST)" 8 7
XTreats ARRAY (@ is optional) as a stack, and pushes the values of LIST
Xonto the end of ARRAY.
XThe length of ARRAY increases by the length of LIST.
XHas the same effect as
X.nf
X
X    for $value (LIST) {
X	    $ARRAY[++$#ARRAY] = $value;
X    }
X
X.fi
Xbut is more efficient.
X.Ip "q/STRING/" 8 5
X.Ip "qq/STRING/" 8
X.Ip "qx/STRING/" 8
XThese are not really functions, but simply syntactic sugar to let you
Xavoid putting too many backslashes into quoted strings.
XThe q operator is a generalized single quote, and the qq operator a
Xgeneralized double quote.
XThe qx operator is a generalized backquote.
XAny non-alphanumeric delimiter can be used in place of /, including newline.
XIf the delimiter is an opening bracket or parenthesis, the final delimiter
Xwill be the corresponding closing bracket or parenthesis.
X(Embedded occurrences of the closing bracket need to be backslashed as usual.)
XExamples:
X.nf
X
X.ne 5
X	$foo = q!I said, "You said, \'She said it.\'"!;
X	$bar = q(\'This is it.\');
X	$today = qx{ date };
X	$_ .= qq
X*** The previous line contains the naughty word "$&".\en
X		if /(ibm|apple|awk)/;      # :-)
X
X.fi
X.Ip "rand(EXPR)" 8 8
X.Ip "rand EXPR" 8
X.Ip "rand" 8
XReturns a random fractional number between 0 and the value of EXPR.
X(EXPR should be positive.)
XIf EXPR is omitted, returns a value between 0 and 1.
XSee also srand().
X.Ip "read(FILEHANDLE,SCALAR,LENGTH,OFFSET)" 8 5
X.Ip "read(FILEHANDLE,SCALAR,LENGTH)" 8 5
XAttempts to read LENGTH bytes of data into variable SCALAR from the specified
XFILEHANDLE.
XReturns the number of bytes actually read, or undef if there was an error.
XSCALAR will be grown or shrunk to the length actually read.
XAn OFFSET may be specified to place the read data at some other place
Xthan the beginning of the string.
XThis call is actually implemented in terms of stdio's fread call.  To get
Xa true read system call, see sysread.
X.Ip "readdir(DIRHANDLE)" 8 3
X.Ip "readdir DIRHANDLE" 8
XReturns the next directory entry for a directory opened by opendir().
XIf used in an array context, returns all the rest of the entries in the
Xdirectory.
XIf there are no more entries, returns an undefined value in a scalar context
Xor a null list in an array context.
X.Ip "readlink(EXPR)" 8 6
X.Ip "readlink EXPR" 8
XReturns the value of a symbolic link, if symbolic links are implemented.
XIf not, gives a fatal error.
XIf there is some system error, returns the undefined value and sets $! (errno).
XIf EXPR is omitted, uses $_.
X.Ip "recv(SOCKET,SCALAR,LEN,FLAGS)" 8 4
XReceives a message on a socket.
XAttempts to receive LENGTH bytes of data into variable SCALAR from the specified
XSOCKET filehandle.
XReturns the address of the sender, or the undefined value if there's an error.
XSCALAR will be grown or shrunk to the length actually read.
XTakes the same flags as the system call of the same name.
X.Ip "redo LABEL" 8 8
X.Ip "redo" 8
XThe
X.I redo
Xcommand restarts the loop block without evaluating the conditional again.
XThe
X.I continue
Xblock, if any, is not executed.
XIf the LABEL is omitted, the command refers to the innermost enclosing loop.
XThis command is normally used by programs that want to lie to themselves
Xabout what was just input:
X.nf
X
X.ne 16
X	# a simpleminded Pascal comment stripper
X	# (warning: assumes no { or } in strings)
X	line: while (<STDIN>) {
X		while (s|\|({.*}.*\|){.*}|$1 \||) {}
X		s|{.*}| \||;
X		if (s|{.*| \||) {
X			$front = $_;
X			while (<STDIN>) {
X				if (\|/\|}/\|) {	# end of comment?
X					s|^|$front{|;
X					redo line;
X				}
X			}
X		}
X		print;
X	}
X
X.fi
X.Ip "rename(OLDNAME,NEWNAME)" 8 2
XChanges the name of a file.
XReturns 1 for success, 0 otherwise.
XWill not work across filesystem boundaries.
X.Ip "require(EXPR)" 8 6
X.Ip "require EXPR" 8
X.Ip "require" 8
XIncludes the library file specified by EXPR, or by $_ if EXPR is not supplied.
XHas semantics similar to the following subroutine:
X.nf
X
X	sub require {
X	    local($filename) = @_;
X	    return 1 if $INC{$filename};
X	    local($realfilename,$result);
X	    ITER: {
X		foreach $prefix (@INC) {
X		    $realfilename = "$prefix/$filename";
X		    if (-f $realfilename) {
X			$result = do $realfilename;
X			last ITER;
X		    }
X		}
X		die "Can't find $filename in \e@INC";
X	    }
X	    die $@ if $@;
X	    die "$filename did not return true value" unless $result;
X	    $INC{$filename} = $realfilename;
X	    $result;
X	}
X
X.fi
XNote that the file will not be included twice under the same specified name.
X.Ip "reset(EXPR)" 8 6
X.Ip "reset EXPR" 8
X.Ip "reset" 8
XGenerally used in a
X.I continue
Xblock at the end of a loop to clear variables and reset ?? searches
Xso that they work again.
XThe expression is interpreted as a list of single characters (hyphens allowed
Xfor ranges).
XAll variables and arrays beginning with one of those letters are reset to
Xtheir pristine state.
XIf the expression is omitted, one-match searches (?pattern?) are reset to
Xmatch again.
XOnly resets variables or searches in the current package.
XAlways returns 1.
XExamples:
X.nf
X
X.ne 3
X    reset \'X\';	\h'|2i'# reset all X variables
X    reset \'a\-z\';\h'|2i'# reset lower case variables
X    reset;	\h'|2i'# just reset ?? searches
X
X.fi
XNote: resetting \*(L"A\-Z\*(R" is not recommended since you'll wipe out your ARGV and ENV
Xarrays.
X.Sp
XThe use of reset on dbm associative arrays does not change the dbm file.
X(It does, however, flush any entries cached by perl, which may be useful if
Xyou are sharing the dbm file.
XThen again, maybe not.)
X.Ip "return LIST" 8 3
XReturns from a subroutine with the value specified.
X(Note that a subroutine can automatically return
Xthe value of the last expression evaluated.
XThat's the preferred method\*(--use of an explicit
X.I return
Xis a bit slower.)
X.Ip "reverse(LIST)" 8 4
X.Ip "reverse LIST" 8
XIn an array context, returns an array value consisting of the elements
Xof LIST in the opposite order.
XIn a scalar context, returns a string value consisting of the bytes of
Xthe first element of LIST in the opposite order.
X.Ip "rewinddir(DIRHANDLE)" 8 5
X.Ip "rewinddir DIRHANDLE" 8
XSets the current position to the beginning of the directory for the readdir() routine on DIRHANDLE.
X.Ip "rindex(STR,SUBSTR,POSITION)" 8 6
X.Ip "rindex(STR,SUBSTR)" 8 4
XWorks just like index except that it
Xreturns the position of the LAST occurrence of SUBSTR in STR.
XIf POSITION is specified, returns the last occurrence at or before that
Xposition.
X.Ip "rmdir(FILENAME)" 8 4
X.Ip "rmdir FILENAME" 8
XDeletes the directory specified by FILENAME if it is empty.
XIf it succeeds it returns 1, otherwise it returns 0 and sets $! (errno).
XIf FILENAME is omitted, uses $_.
X.Ip "s/PATTERN/REPLACEMENT/gieo" 8 3
XSearches a string for a pattern, and if found, replaces that pattern with the
Xreplacement text and returns the number of substitutions made.
XOtherwise it returns false (0).
XThe \*(L"g\*(R" is optional, and if present, indicates that all occurrences
Xof the pattern are to be replaced.
XThe \*(L"i\*(R" is also optional, and if present, indicates that matching
Xis to be done in a case-insensitive manner.
XThe \*(L"e\*(R" is likewise optional, and if present, indicates that
Xthe replacement string is to be evaluated as an expression rather than just
Xas a double-quoted string.
XAny non-alphanumeric delimiter may replace the slashes;
Xif single quotes are used, no
Xinterpretation is done on the replacement string (the e modifier overrides
Xthis, however); if backquotes are used, the replacement string is a command
Xto execute whose output will be used as the actual replacement text.
XIf no string is specified via the =~ or !~ operator,
Xthe $_ string is searched and modified.
X(The string specified with =~ must be a scalar variable, an array element,
Xor an assignment to one of those, i.e. an lvalue.)
XIf the pattern contains a $ that looks like a variable rather than an
Xend-of-string test, the variable will be interpolated into the pattern at
Xrun-time.
XIf you only want the pattern compiled once the first time the variable is
Xinterpolated, add an \*(L"o\*(R" at the end.
XIf the PATTERN evaluates to a null string, the most recent successful
Xregular expression is used instead.
XSee also the section on regular expressions.
XExamples:
X.nf
X
X    s/\|\e\|bgreen\e\|b/mauve/g;		# don't change wintergreen
X
X    $path \|=~ \|s|\|/usr/bin|\|/usr/local/bin|;
X
X    s/Login: $foo/Login: $bar/; # run-time pattern
X
X    ($foo = $bar) =~ s/bar/foo/;
X
X    $_ = \'abc123xyz\';
X    s/\ed+/$&*2/e;		# yields \*(L'abc246xyz\*(R'
X    s/\ed+/sprintf("%5d",$&)/e;	# yields \*(L'abc  246xyz\*(R'
X    s/\ew/$& x 2/eg;		# yields \*(L'aabbcc  224466xxyyzz\*(R'
X
X    s/\|([^ \|]*\|) *\|([^ \|]*\|)\|/\|$2 $1/;	# reverse 1st two fields
X
X.fi
X(Note the use of $ instead of \|\e\| in the last example.  See section
Xon regular expressions.)
X.Ip "scalar(EXPR)" 8 3
XForces EXPR to be interpreted in a scalar context and returns the value
Xof EXPR.
X.Ip "seek(FILEHANDLE,POSITION,WHENCE)" 8 3
XRandomly positions the file pointer for FILEHANDLE, just like the fseek()
Xcall of stdio.
XFILEHANDLE may be an expression whose value gives the name of the filehandle.
XReturns 1 upon success, 0 otherwise.
X.Ip "seekdir(DIRHANDLE,POS)" 8 3
XSets the current position for the readdir() routine on DIRHANDLE.
XPOS must be a value returned by telldir().
XHas the same caveats about possible directory compaction as the corresponding
Xsystem library routine.
X.Ip "select(FILEHANDLE)" 8 3
X.Ip "select" 8 3
XReturns the currently selected filehandle.
XSets the current default filehandle for output, if FILEHANDLE is supplied.
XThis has two effects: first, a
X.I write
Xor a
X.I print
Xwithout a filehandle will default to this FILEHANDLE.
XSecond, references to variables related to output will refer to this output
Xchannel.
XFor example, if you have to set the top of form format for more than
Xone output channel, you might do the following:
X.nf
X
X.ne 4
X	select(REPORT1);
X	$^ = \'report1_top\';
X	select(REPORT2);
X	$^ = \'report2_top\';
X
X.fi
XFILEHANDLE may be an expression whose value gives the name of the actual filehandle.
XThus:
X.nf
X
X	$oldfh = select(STDERR); $| = 1; select($oldfh);
X
X.fi
X.Ip "select(RBITS,WBITS,EBITS,TIMEOUT)" 8 3
XThis calls the select system call with the bitmasks specified, which can
Xbe constructed using fileno() and vec(), along these lines:
X.nf
X
X	$rin = $win = $ein = '';
X	vec($rin,fileno(STDIN),1) = 1;
X	vec($win,fileno(STDOUT),1) = 1;
X	$ein = $rin | $win;
X
X.fi
XIf you want to select on many filehandles you might wish to write a subroutine:
X.nf
X
X	sub fhbits {
X	    local(@fhlist) = split(' ',$_[0]);
X	    local($bits);
X	    for (@fhlist) {
X		vec($bits,fileno($_),1) = 1;
X	    }
X	    $bits;
X	}
X	$rin = &fhbits('STDIN TTY SOCK');
X
X.fi
XThe usual idiom is:
X.nf
X
X	($nfound,$timeleft) =
X	  select($rout=$rin, $wout=$win, $eout=$ein, $timeout);
X
Xor to block until something becomes ready:
X
X.ie t \{\
X	$nfound = select($rout=$rin, $wout=$win, $eout=$ein, undef);
X'br\}
X.el \{\
X	$nfound = select($rout=$rin, $wout=$win,
X				$eout=$ein, undef);
X'br\}
X
X.fi
XAny of the bitmasks can also be undef.
XThe timeout, if specified, is in seconds, which may be fractional.
XNOTE: not all implementations are capable of returning the $timeleft.
XIf not, they always return $timeleft equal to the supplied $timeout.
X.Ip "semctl(ID,SEMNUM,CMD,ARG)" 8 4
XCalls the System V IPC function semctl.  If CMD is &IPC_STAT or
X&GETALL, then ARG must be a variable which will hold the returned
Xsemid_ds structure or semaphore value array.  Returns like ioctl: the
Xundefined value for error, "0 but true" for zero, or the actual return
Xvalue otherwise.
X.Ip "semget(KEY,NSEMS,SIZE,FLAGS)" 8 4
XCalls the System V IPC function semget.  Returns the semaphore id, or
Xthe undefined value if there is an error.
X.Ip "semop(KEY,OPSTRING)" 8 4
XCalls the System V IPC function semop to perform semaphore operations
Xsuch as signaling and waiting.  OPSTRING must be a packed array of
Xsemop structures.  Each semop structure can be generated with
X\&'pack("sss", $semnum, $semop, $semflag)'.  The number of semaphore
Xoperations is implied by the length of OPSTRING.  Returns true if
Xsuccessful, or false if there is an error.  As an example, the
Xfollowing code waits on semaphore $semnum of semaphore id $semid:
X.nf
X
X	$semop = pack("sss", $semnum, -1, 0);
X	die "Semaphore trouble: $!\en" unless semop($semid, $semop);
X
X.fi
XTo signal the semaphore, replace "-1" with "1".
X.Ip "send(SOCKET,MSG,FLAGS,TO)" 8 4
X.Ip "send(SOCKET,MSG,FLAGS)" 8
XSends a message on a socket.
XTakes the same flags as the system call of the same name.
XOn unconnected sockets you must specify a destination to send TO.
XReturns the number of characters sent, or the undefined value if
Xthere is an error.
X.Ip "setpgrp(PID,PGRP)" 8 4
XSets the current process group for the specified PID, 0 for the current
Xprocess.
XWill produce a fatal error if used on a machine that doesn't implement
Xsetpgrp(2).
X.Ip "setpriority(WHICH,WHO,PRIORITY)" 8 4
XSets the current priority for a process, a process group, or a user.
X(See setpriority(2).)
XWill produce a fatal error if used on a machine that doesn't implement
Xsetpriority(2).
X.Ip "setsockopt(SOCKET,LEVEL,OPTNAME,OPTVAL)" 8 3
XSets the socket option requested.
XReturns undefined if there is an error.
XOPTVAL may be specified as undef if you don't want to pass an argument.
X.Ip "shift(ARRAY)" 8 6
X.Ip "shift ARRAY" 8
X.Ip "shift" 8
XShifts the first value of the array off and returns it,
Xshortening the array by 1 and moving everything down.
XIf there are no elements in the array, returns the undefined value.
XIf ARRAY is omitted, shifts the @ARGV array in the main program, and the @_
Xarray in subroutines.
X(This is determined lexically.)
XSee also unshift(), push() and pop().
XShift() and unshift() do the same thing to the left end of an array that push()
Xand pop() do to the right end.
X.Ip "shmctl(ID,CMD,ARG)" 8 4
XCalls the System V IPC function shmctl.  If CMD is &IPC_STAT, then ARG
Xmust be a variable which will hold the returned shmid_ds structure.
XReturns like ioctl: the undefined value for error, "0 but true" for
Xzero, or the actual return value otherwise.
X.Ip "shmget(KEY,SIZE,FLAGS)" 8 4
XCalls the System V IPC function shmget.  Returns the shared memory
Xsegment id, or the undefined value if there is an error.
X.Ip "shmread(ID,VAR,POS,SIZE)" 8 4
X.Ip "shmwrite(ID,STRING,POS,SIZE)" 8
XReads or writes the System V shared memory segment ID starting at
Xposition POS for size SIZE by attaching to it, copying in/out, and
Xdetaching from it.  When reading, VAR must be a variable which
Xwill hold the data read.  When writing, if STRING is too long,
Xonly SIZE bytes are used; if STRING is too short, nulls are
Xwritten to fill out SIZE bytes.  Return true if successful, or
Xfalse if there is an error.
X.Ip "shutdown(SOCKET,HOW)" 8 3
XShuts down a socket connection in the manner indicated by HOW, which has
Xthe same interpretation as in the system call of the same name.
X.Ip "sin(EXPR)" 8 4
X.Ip "sin EXPR" 8
XReturns the sine of EXPR (expressed in radians).
XIf EXPR is omitted, returns sine of $_.
X.Ip "sleep(EXPR)" 8 6
X.Ip "sleep EXPR" 8
X.Ip "sleep" 8
XCauses the script to sleep for EXPR seconds, or forever if no EXPR.
XMay be interrupted by sending the process a SIGALARM.
XReturns the number of seconds actually slept.
X.Ip "socket(SOCKET,DOMAIN,TYPE,PROTOCOL)" 8 3
XOpens a socket of the specified kind and attaches it to filehandle SOCKET.
XDOMAIN, TYPE and PROTOCOL are specified the same as for the system call
Xof the same name.
XYou may need to run h2ph on sys/socket.h to get the proper values handy
Xin a perl library file.
XReturn true if successful.
XSee the example in the section on Interprocess Communication.
X.Ip "socketpair(SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL)" 8 3
XCreates an unnamed pair of sockets in the specified domain, of the specified
Xtype.
XDOMAIN, TYPE and PROTOCOL are specified the same as for the system call
Xof the same name.
XIf unimplemented, yields a fatal error.
XReturn true if successful.
X.Ip "sort(SUBROUTINE LIST)" 8 9
X.Ip "sort(LIST)" 8
X.Ip "sort SUBROUTINE LIST" 8
X.Ip "sort LIST" 8
XSorts the LIST and returns the sorted array value.
XNonexistent values of arrays are stripped out.
XIf SUBROUTINE is omitted, sorts in standard string comparison order.
XIf SUBROUTINE is specified, gives the name of a subroutine that returns
Xan integer less than, equal to, or greater than 0,
Xdepending on how the elements of the array are to be ordered.
XIn the interests of efficiency the normal calling code for subroutines
Xis bypassed, with the following effects: the subroutine may not be a recursive
Xsubroutine, and the two elements to be compared are passed into the subroutine
Xnot via @_ but as $a and $b (see example below).
XThey are passed by reference so don't modify $a and $b.
XSUBROUTINE may be a scalar variable name, in which case the value provides
Xthe name of the subroutine to use.
XExamples:
X.nf
X
X.ne 4
X	sub byage {
X	    $age{$a} - $age{$b};	# presuming integers
X	}
X	@sortedclass = sort byage @class;
X
X.ne 9
X	sub reverse { $a lt $b ? 1 : $a gt $b ? \-1 : 0; }
X	@harry = (\'dog\',\'cat\',\'x\',\'Cain\',\'Abel\');
X	@george = (\'gone\',\'chased\',\'yz\',\'Punished\',\'Axed\');
X	print sort @harry;
X		# prints AbelCaincatdogx
X	print sort reverse @harry;
X		# prints xdogcatCainAbel
X	print sort @george, \'to\', @harry;
X		# prints AbelAxedCainPunishedcatchaseddoggonetoxyz
X
X.fi
X.Ip "splice(ARRAY,OFFSET,LENGTH,LIST)" 8 8
X.Ip "splice(ARRAY,OFFSET,LENGTH)" 8
X.Ip "splice(ARRAY,OFFSET)" 8
XRemoves the elements designated by OFFSET and LENGTH from an array, and
Xreplaces them with the elements of LIST, if any.
XReturns the elements removed from the array.
XThe array grows or shrinks as necessary.
XIf LENGTH is omitted, removes everything from OFFSET onward.
XThe following equivalencies hold (assuming $[ == 0):
X.nf
X
X	push(@a,$x,$y)\h'|3.5i'splice(@a,$#a+1,0,$x,$y)
X	pop(@a)\h'|3.5i'splice(@a,-1)
X	shift(@a)\h'|3.5i'splice(@a,0,1)
X	unshift(@a,$x,$y)\h'|3.5i'splice(@a,0,0,$x,$y)
X	$a[$x] = $y\h'|3.5i'splice(@a,$x,1,$y);
X
XExample, assuming array lengths are passed before arrays:
X	
X	sub aeq {	# compare two array values
X		local(@a) = splice(@_,0,shift);
X		local(@b) = splice(@_,0,shift);
X		return 0 unless @a == @b;	# same len?
X		while (@a) {
X		    return 0 if pop(@a) ne pop(@b);
X		}
X		return 1;
X	}
X	if (&aeq($len,@foo[1..$len],0+@bar,@bar)) { ... }
X
X.fi
X.Ip "split(/PATTERN/,EXPR,LIMIT)" 8 8
X.Ip "split(/PATTERN/,EXPR)" 8 8
X.Ip "split(/PATTERN/)" 8
X.Ip "split" 8
XSplits a string into an array of strings, and returns it.
X(If not in an array context, returns the number of fields found and splits
Xinto the @_ array.
X(In an array context, you can force the split into @_
Xby using ?? as the pattern delimiters, but it still returns the array value.))
XIf EXPR is omitted, splits the $_ string.
XIf PATTERN is also omitted, splits on whitespace (/[\ \et\en]+/).
XAnything matching PATTERN is taken to be a delimiter separating the fields.
X(Note that the delimiter may be longer than one character.)
XIf LIMIT is specified, splits into no more than that many fields (though it
Xmay split into fewer).
XIf LIMIT is unspecified, trailing null fields are stripped (which
Xpotential users of pop() would do well to remember).
XA pattern matching the null string (not to be confused with a null pattern //,
Xwhich is just one member of the set of patterns matching a null string)
Xwill split the value of EXPR into separate characters at each point it
Xmatches that way.
XFor example:
X.nf
X
X	print join(\':\', split(/ */, \'hi there\'));
X
X.fi
Xproduces the output \*(L'h:i:t:h:e:r:e\*(R'.
X.Sp
XThe LIMIT parameter can be used to partially split a line
X.nf
X
X	($login, $passwd, $remainder) = split(\|/\|:\|/\|, $_, 3);
X
X.fi
X(When assigning to a list, if LIMIT is omitted, perl supplies a LIMIT one
Xlarger than the number of variables in the list, to avoid unnecessary work.
XFor the list above LIMIT would have been 4 by default.
XIn time critical applications it behooves you not to split into
Xmore fields than you really need.)
X.Sp
XIf the PATTERN contains parentheses, additional array elements are created
Xfrom each matching substring in the delimiter.
X.Sp
X	split(/([,-])/,"1-10,20");
X.Sp
Xproduces the array value
X.Sp
X	(1,'-',10,',',20)
X.Sp
XThe pattern /PATTERN/ may be replaced with an expression to specify patterns
Xthat vary at runtime.
X(To do runtime compilation only once, use /$variable/o.)
XAs a special case, specifying a space (\'\ \') will split on white space
Xjust as split with no arguments does, but leading white space does NOT
Xproduce a null first field.
XThus, split(\'\ \') can be used to emulate
X.IR awk 's
Xdefault behavior, whereas
Xsplit(/\ /) will give you as many null initial fields as there are
Xleading spaces.
X.Sp
XExample:
X.nf
X
X.ne 5
X	open(passwd, \'/etc/passwd\');
X	while (<passwd>) {
X.ie t \{\
X		($login, $passwd, $uid, $gid, $gcos, $home, $shell) = split(\|/\|:\|/\|);
X'br\}
X.el \{\
X		($login, $passwd, $uid, $gid, $gcos, $home, $shell)
X			= split(\|/\|:\|/\|);
X'br\}
X		.\|.\|.
X	}
X
X.fi
X(Note that $shell above will still have a newline on it.  See chop().)
XSee also
X.IR join .
X.Ip "sprintf(FORMAT,LIST)" 8 4
XReturns a string formatted by the usual printf conventions.
XThe * character is not supported.
X.Ip "sqrt(EXPR)" 8 4
X.Ip "sqrt EXPR" 8
XReturn the square root of EXPR.
XIf EXPR is omitted, returns square root of $_.
X.Ip "srand(EXPR)" 8 4
X.Ip "srand EXPR" 8
XSets the random number seed for the
X.I rand
Xoperator.
XIf EXPR is omitted, does srand(time).
X.Ip "stat(FILEHANDLE)" 8 8
X.Ip "stat FILEHANDLE" 8
X.Ip "stat(EXPR)" 8
X.Ip "stat SCALARVARIABLE" 8
XReturns a 13-element array giving the statistics for a file, either the file
Xopened via FILEHANDLE, or named by EXPR.
XTypically used as follows:
X.nf
X
X.ne 3
X    ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
X       $atime,$mtime,$ctime,$blksize,$blocks)
X           = stat($filename);
X
X.fi
XIf stat is passed the special filehandle consisting of an underline,
Xno stat is done, but the current contents of the stat structure from
Xthe last stat or filetest are returned.
XExample:
X.nf
X
X.ne 3
X	if (-x $file && (($d) = stat(_)) && $d < 0) {
X		print "$file is executable NFS file\en";
X	}
X
X.fi
X.Ip "study(SCALAR)" 8 6
X.Ip "study SCALAR" 8
X.Ip "study"
XTakes extra time to study SCALAR ($_ if unspecified) in anticipation of
Xdoing many pattern matches on the string before it is next modified.
XThis may or may not save time, depending on the nature and number of patterns
Xyou are searching on, and on the distribution of character frequencies in
Xthe string to be searched\*(--you probably want to compare runtimes with and
Xwithout it to see which runs faster.
XThose loops which scan for many short constant strings (including the constant
Xparts of more complex patterns) will benefit most.
XYou may have only one study active at a time\*(--if you study a different
Xscalar the first is \*(L"unstudied\*(R".
X(The way study works is this: a linked list of every character in the string
Xto be searched is made, so we know, for example, where all the \*(L'k\*(R' characters
Xare.
XFrom each search string, the rarest character is selected, based on some
Xstatic frequency tables constructed from some C programs and English text.
XOnly those places that contain this \*(L"rarest\*(R" character are examined.)
X.Sp
XFor example, here is a loop which inserts index producing entries before any line
Xcontaining a certain pattern:
X.nf
X
X.ne 8
X	while (<>) {
X		study;
X		print ".IX foo\en" if /\ebfoo\eb/;
X		print ".IX bar\en" if /\ebbar\eb/;
X		print ".IX blurfl\en" if /\ebblurfl\eb/;
X		.\|.\|.
X		print;
X	}
X
X.fi
XIn searching for /\ebfoo\eb/, only those locations in $_ that contain \*(L'f\*(R'
Xwill be looked at, because \*(L'f\*(R' is rarer than \*(L'o\*(R'.
XIn general, this is a big win except in pathological cases.
XThe only question is whether it saves you more time than it took to build
Xthe linked list in the first place.
X.Sp
XNote that if you have to look for strings that you don't know till runtime,
Xyou can build an entire loop as a string and eval that to avoid recompiling
Xall your patterns all the time.
XTogether with undefining $/ to input entire files as one record, this can
Xbe very fast, often faster than specialized programs like fgrep.
XThe following scans a list of files (@files)
Xfor a list of words (@words), and prints out the names of those files that
Xcontain a match:
X.nf
X
X.ne 12
X	$search = \'while (<>) { study;\';
X	foreach $word (@words) {
X	    $search .= "++\e$seen{\e$ARGV} if /\eb$word\eb/;\en";
X	}
X	$search .= "}";
X	@ARGV = @files;
X	undef $/;
X	eval $search;		# this screams
X	$/ = "\en";		# put back to normal input delim
X	foreach $file (sort keys(%seen)) {
X	    print $file, "\en";
X	}
X
X.fi
X.Ip "substr(EXPR,OFFSET,LEN)" 8 2
X.Ip "substr(EXPR,OFFSET)" 8 2
XExtracts a substring out of EXPR and returns it.
XFirst character is at offset 0, or whatever you've set $[ to.
XIf OFFSET is negative, starts that far from the end of the string.
XIf LEN is omitted, returns everything to the end of the string.
XYou can use the substr() function as an lvalue, in which case EXPR must
Xbe an lvalue.
XIf you assign something shorter than LEN, the string will shrink, and
Xif you assign something longer than LEN, the string will grow to accommodate it.
XTo keep the string the same length you may need to pad or chop your value using
Xsprintf().
X.Ip "symlink(OLDFILE,NEWFILE)" 8 2
XCreates a new filename symbolically linked to the old filename.
XReturns 1 for success, 0 otherwise.
XOn systems that don't support symbolic links, produces a fatal error at
Xrun time.
XTo check for that, use eval:
X.nf
X
X	$symlink_exists = (eval \'symlink("","");\', $@ eq \'\');
X
X.fi
X.Ip "syscall(LIST)" 8 6
X.Ip "syscall LIST" 8
XCalls the system call specified as the first element of the list, passing
Xthe remaining elements as arguments to the system call.
XIf unimplemented, produces a fatal error.
XThe arguments are interpreted as follows: if a given argument is numeric,
Xthe argument is passed as an int.
XIf not, the pointer to the string value is passed.
XYou are responsible to make sure a string is pre-extended long enough
Xto receive any result that might be written into a string.
XIf your integer arguments are not literals and have never been interpreted
Xin a numeric context, you may need to add 0 to them to force them to look
Xlike numbers.
X.nf
X
X	require 'syscall.ph';		# may need to run h2ph
X	syscall(&SYS_write, fileno(STDOUT), "hi there\en", 9);
X
X.fi
X.Ip "sysread(FILEHANDLE,SCALAR,LENGTH,OFFSET)" 8 5
X.Ip "sysread(FILEHANDLE,SCALAR,LENGTH)" 8 5
XAttempts to read LENGTH bytes of data into variable SCALAR from the specified
XFILEHANDLE, using the system call read(2).
XIt bypasses stdio, so mixing this with other kinds of reads may cause
Xconfusion.
XReturns the number of bytes actually read, or undef if there was an error.
XSCALAR will be grown or shrunk to the length actually read.
XAn OFFSET may be specified to place the read data at some other place
Xthan the beginning of the string.
X.Ip "system(LIST)" 8 6
X.Ip "system LIST" 8
XDoes exactly the same thing as \*(L"exec LIST\*(R" except that a fork
Xis done first, and the parent process waits for the child process to complete.
XNote that argument processing varies depending on the number of arguments.
XThe return value is the exit status of the program as returned by the wait()
Xcall.
XTo get the actual exit value divide by 256.
XSee also
X.IR exec .
X.Ip "syswrite(FILEHANDLE,SCALAR,LENGTH,OFFSET)" 8 5
X.Ip "syswrite(FILEHANDLE,SCALAR,LENGTH)" 8 5
XAttempts to write LENGTH bytes of data from variable SCALAR to the specified
XFILEHANDLE, using the system call write(2).
XIt bypasses stdio, so mixing this with prints may cause
Xconfusion.
XReturns the number of bytes actually written, or undef if there was an error.
XAn OFFSET may be specified to place the read data at some other place
Xthan the beginning of the string.
X.Ip "tell(FILEHANDLE)" 8 6
X.Ip "tell FILEHANDLE" 8 6
X.Ip "tell" 8
XReturns the current file position for FILEHANDLE.
XFILEHANDLE may be an expression whose value gives the name of the actual
Xfilehandle.
XIf FILEHANDLE is omitted, assumes the file last read.
X.Ip "telldir(DIRHANDLE)" 8 5
X.Ip "telldir DIRHANDLE" 8
XReturns the current position of the readdir() routines on DIRHANDLE.
XValue may be given to seekdir() to access a particular location in
Xa directory.
XHas the same caveats about possible directory compaction as the corresponding
Xsystem library routine.
X.Ip "time" 8 4
XReturns the number of non-leap seconds since 00:00:00 UTC, January 1, 1970.
XSuitable for feeding to gmtime() and localtime().
X.Ip "times" 8 4
XReturns a four-element array giving the user and system times, in seconds, for this
Xprocess and the children of this process.
X.Sp
X    ($user,$system,$cuser,$csystem) = times;
X.Sp
X.Ip "tr/SEARCHLIST/REPLACEMENTLIST/cds" 8 5
X.Ip "y/SEARCHLIST/REPLACEMENTLIST/cds" 8
XTranslates all occurrences of the characters found in the search list with
Xthe corresponding character in the replacement list.
XIt returns the number of characters replaced or deleted.
XIf no string is specified via the =~ or !~ operator,
Xthe $_ string is translated.
X(The string specified with =~ must be a scalar variable, an array element,
Xor an assignment to one of those, i.e. an lvalue.)
XFor
X.I sed
Xdevotees,
X.I y
Xis provided as a synonym for
X.IR tr .
X.Sp
XIf the c modifier is specified, the SEARCHLIST character set is complemented.
XIf the d modifier is specified, any characters specified by SEARCHLIST that
Xare not found in REPLACEMENTLIST are deleted.
X(Note that this is slightly more flexible than the behavior of some
X.I tr
Xprograms, which delete anything they find in the SEARCHLIST, period.)
XIf the s modifier is specified, sequences of characters that were translated
Xto the same character are squashed down to 1 instance of the character.
X.Sp
XIf the d modifier was used, the REPLACEMENTLIST is always interpreted exactly
Xas specified.
XOtherwise, if the REPLACEMENTLIST is shorter than the SEARCHLIST,
Xthe final character is replicated till it is long enough.
XIf the REPLACEMENTLIST is null, the SEARCHLIST is replicated.
XThis latter is useful for counting characters in a class, or for squashing
Xcharacter sequences in a class.
X.Sp
XExamples:
X.nf
X
X    $ARGV[1] \|=~ \|y/A\-Z/a\-z/;	\h'|3i'# canonicalize to lower case
X
X    $cnt = tr/*/*/;		\h'|3i'# count the stars in $_
X
X    $cnt = tr/0\-9//;		\h'|3i'# count the digits in $_
X
X    tr/a\-zA\-Z//s;	\h'|3i'# bookkeeper \-> bokeper
X
X    ($HOST = $host) =~ tr/a\-z/A\-Z/;
X
X    y/a\-zA\-Z/ /cs;	\h'|3i'# change non-alphas to single space
X
X    tr/\e200\-\e377/\e0\-\e177/;\h'|3i'# delete 8th bit
X
X.fi
X.Ip "truncate(FILEHANDLE,LENGTH)" 8 4
X.Ip "truncate(EXPR,LENGTH)" 8
XTruncates the file opened on FILEHANDLE, or named by EXPR, to the specified
Xlength.
XProduces a fatal error if truncate isn't implemented on your system.
X.Ip "umask(EXPR)" 8 4
X.Ip "umask EXPR" 8
X.Ip "umask" 8
XSets the umask for the process and returns the old one.
XIf EXPR is omitted, merely returns current umask.
X.Ip "undef(EXPR)" 8 6
X.Ip "undef EXPR" 8
X.Ip "undef" 8
XUndefines the value of EXPR, which must be an lvalue.
XUse only on a scalar value, an entire array, or a subroutine name (using &).
X(Undef will probably not do what you expect on most predefined variables or
Xdbm array values.)
XAlways returns the undefined value.
XYou can omit the EXPR, in which case nothing is undefined, but you still
Xget an undefined value that you could, for instance, return from a subroutine.
XExamples:
X.nf
X
X.ne 6
X	undef $foo;
X	undef $bar{'blurfl'};
X	undef @ary;
X	undef %assoc;
X	undef &mysub;
X	return (wantarray ? () : undef) if $they_blew_it;
X
X.fi
X.Ip "unlink(LIST)" 8 4
X.Ip "unlink LIST" 8
XDeletes a list of files.
XReturns the number of files successfully deleted.
X.nf
X
X.ne 2
X	$cnt = unlink \'a\', \'b\', \'c\';
X	unlink @goners;
X	unlink <*.bak>;
X
X.fi
XNote: unlink will not delete directories unless you are superuser and the
X.B \-U
Xflag is supplied to
X.IR perl .
XEven if these conditions are met, be warned that unlinking a directory
Xcan inflict damage on your filesystem.
XUse rmdir instead.
X.Ip "unpack(TEMPLATE,EXPR)" 8 4
XUnpack does the reverse of pack: it takes a string representing
Xa structure and expands it out into an array value, returning the array
Xvalue.
X(In a scalar context, it merely returns the first value produced.)
XThe TEMPLATE has the same format as in the pack function.
XHere's a subroutine that does substring:
X.nf
X
X.ne 4
X	sub substr {
X		local($what,$where,$howmuch) = @_;
X		unpack("x$where a$howmuch", $what);
X	}
X
X.ne 3
Xand then there's
X
X	sub ord { unpack("c",$_[0]); }
X
X.fi
XIn addition, you may prefix a field with a %<number> to indicate that
Xyou want a <number>-bit checksum of the items instead of the items themselves.
XDefault is a 16-bit checksum.
XFor example, the following computes the same number as the System V sum program:
X.nf
X
X.ne 4
X	while (<>) {
X	    $checksum += unpack("%16C*", $_);
X	}
X	$checksum %= 65536;
X
X.fi
X.Ip "unshift(ARRAY,LIST)" 8 4
XDoes the opposite of a
X.IR shift .
XOr the opposite of a
X.IR push ,
Xdepending on how you look at it.
XPrepends list to the front of the array, and returns the number of elements
Xin the new array.
X.nf
X
X	unshift(ARGV, \'\-e\') unless $ARGV[0] =~ /^\-/;
X
X.fi
X.Ip "utime(LIST)" 8 2
X.Ip "utime LIST" 8 2
XChanges the access and modification times on each file of a list of files.
XThe first two elements of the list must be the NUMERICAL access and
Xmodification times, in that order.
XReturns the number of files successfully changed.
XThe inode modification time of each file is set to the current time.
XExample of a \*(L"touch\*(R" command:
X.nf
X
X.ne 3
X	#!/usr/bin/perl
X	$now = time;
X	utime $now, $now, @ARGV;
X
X.fi
X.Ip "values(ASSOC_ARRAY)" 8 6
X.Ip "values ASSOC_ARRAY" 8
XReturns a normal array consisting of all the values of the named associative
Xarray.
XThe values are returned in an apparently random order, but it is the same order
Xas either the keys() or each() function would produce on the same array.
XSee also keys() and each().
X.Ip "vec(EXPR,OFFSET,BITS)" 8 2
XTreats a string as a vector of unsigned integers, and returns the value
Xof the bitfield specified.
XMay also be assigned to.
XBITS must be a power of two from 1 to 32.
X.Sp
XVectors created with vec() can also be manipulated with the logical operators
X|, & and ^,
Xwhich will assume a bit vector operation is desired when both operands are
Xstrings.
XThis interpretation is not enabled unless there is at least one vec() in
Xyour program, to protect older programs.
X.Sp
XTo transform a bit vector into a string or array of 0's and 1's, use these:
X.nf
X
X	$bits = unpack("b*", $vector);
X	@bits = split(//, unpack("b*", $vector));
X
X.fi
XIf you know the exact length in bits, it can be used in place of the *.
X.Ip "wait" 8 6
XWaits for a child process to terminate and returns the pid of the deceased
Xprocess, or -1 if there are no child processes.
XThe status is returned in $?.
X.Ip "waitpid(PID,FLAGS)" 8 6
XWaits for a particular child process to terminate and returns the pid of the deceased
Xprocess, or -1 if there is no such child process.
XThe status is returned in $?.
XIf you say
X.nf
X
X	require "sys/wait.h";
X	.\|.\|.
X	waitpid(-1,&WNOHANG);
X
X.fi
Xthen you can do a non-blocking wait for any process.  Non-blocking wait
Xis only available on machines supporting either the
X.I waitpid (2)
Xor
X.I wait4 (2)
Xsystem calls.
XHowever, waiting for a particular pid with FLAGS of 0 is implemented
Xeverywhere.  (Perl emulates the system call by remembering the status
Xvalues of processes that have exited but have not been harvested by the
XPerl script yet.)
X.Ip "wantarray" 8 4
XReturns true if the context of the currently executing subroutine
Xis looking for an array value.
XReturns false if the context is looking for a scalar.
X.nf
X
X	return wantarray ? () : undef;
X
X.fi
X.Ip "warn(LIST)" 8 4
X.Ip "warn LIST" 8
XProduces a message on STDERR just like \*(L"die\*(R", but doesn't exit.
X.Ip "write(FILEHANDLE)" 8 6
X.Ip "write(EXPR)" 8
X.Ip "write" 8
XWrites a formatted record (possibly multi-line) to the specified file,
Xusing the format associated with that file.
XBy default the format for a file is the one having the same name is the
Xfilehandle, but the format for the current output channel (see
X.IR select )
Xmay be set explicitly
Xby assigning the name of the format to the $~ variable.
X.Sp
XTop of form processing is handled automatically:
Xif there is insufficient room on the current page for the formatted 
Xrecord, the page is advanced by writing a form feed,
Xa special top-of-page format is used
Xto format the new page header, and then the record is written.
XBy default the top-of-page format is \*(L"top\*(R", but it
Xmay be set to the
Xformat of your choice by assigning the name to the $^ variable.
XThe number of lines remaining on the current page is in variable $-, which
Xcan be set to 0 to force a new page.
X.Sp
XIf FILEHANDLE is unspecified, output goes to the current default output channel,
Xwhich starts out as
X.I STDOUT
Xbut may be changed by the
X.I select
Xoperator.
XIf the FILEHANDLE is an EXPR, then the expression is evaluated and the
Xresulting string is used to look up the name of the FILEHANDLE at run time.
XFor more on formats, see the section on formats later on.
X.Sp
XNote that write is NOT the opposite of read.
X''' Beginning of part 4
X''' $RCSfile: perl.man,v $$Revision: 4.0.1.1 $$Date: 91/04/11 17:50:44 $
X'''
X''' $Log:	perl.man,v $
X''' Revision 4.0.1.1  91/04/11  17:50:44  lwall
X''' patch1: fixed some typos
X''' 
X''' Revision 4.0  91/03/20  01:38:08  lwall
X''' 4.0 baseline.
X''' 
X''' Revision 3.0.1.14  91/01/11  18:18:53  lwall
X''' patch42: started an addendum and errata section in the man page
X''' 
X''' Revision 3.0.1.13  90/11/10  01:51:00  lwall
X''' patch38: random cleanup
X''' 
X''' Revision 3.0.1.12  90/10/20  02:15:43  lwall
X''' patch37: patch37: fixed various typos in man page
X''' 
X''' Revision 3.0.1.11  90/10/16  10:04:28  lwall
X''' patch29: added @###.## fields to format
X''' 
X''' Revision 3.0.1.10  90/08/09  04:47:35  lwall
X''' patch19: added require operator
X''' patch19: added numeric interpretation of $]
X''' 
X''' Revision 3.0.1.9  90/08/03  11:15:58  lwall
X''' patch19: Intermediate diffs for Randal
X''' 
X''' Revision 3.0.1.8  90/03/27  16:19:31  lwall
X''' patch16: MSDOS support
X''' 
X''' Revision 3.0.1.7  90/03/14  12:29:50  lwall
X''' patch15: man page falsely states that you can't subscript array values
X''' 
X''' Revision 3.0.1.6  90/03/12  16:54:04  lwall
X''' patch13: improved documentation of *name
X''' 
X''' Revision 3.0.1.5  90/02/28  18:01:52  lwall
X''' patch9: $0 is now always the command name
X''' 
X''' Revision 3.0.1.4  89/12/21  20:12:39  lwall
X''' patch7: documented that package'filehandle works as well as $package'variable
X''' patch7: documented which identifiers are always in package main
X''' 
X''' Revision 3.0.1.3  89/11/17  15:32:25  lwall
X''' patch5: fixed some manual typos and indent problems
X''' patch5: clarified difference between $! and $@
X''' 
X''' Revision 3.0.1.2  89/11/11  04:46:40  lwall
X''' patch2: made some line breaks depend on troff vs. nroff
X''' patch2: clarified operation of ^ and $ when $* is false
X''' 
X''' Revision 3.0.1.1  89/10/26  23:18:43  lwall
X''' patch1: documented the desirability of unnecessary parentheses
X''' 
X''' Revision 3.0  89/10/18  15:21:55  lwall
X''' 3.0 baseline
X''' 
X.Sh "Precedence"
X.I Perl
Xoperators have the following associativity and precedence:
X.nf
X
Xnonassoc\h'|1i'print printf exec system sort reverse
X\h'1.5i'chmod chown kill unlink utime die return
Xleft\h'|1i',
Xright\h'|1i'= += \-= *= etc.
Xright\h'|1i'?:
Xnonassoc\h'|1i'.\|.
Xleft\h'|1i'||
Xleft\h'|1i'&&
Xleft\h'|1i'| ^
Xleft\h'|1i'&
Xnonassoc\h'|1i'== != <=> eq ne cmp
Xnonassoc\h'|1i'< > <= >= lt gt le ge
Xnonassoc\h'|1i'chdir exit eval reset sleep rand umask
Xnonassoc\h'|1i'\-r \-w \-x etc.
Xleft\h'|1i'<< >>
Xleft\h'|1i'+ \- .
Xleft\h'|1i'* / % x
Xleft\h'|1i'=~ !~ 
Xright\h'|1i'! ~ and unary minus
Xright\h'|1i'**
Xnonassoc\h'|1i'++ \-\|\-
Xleft\h'|1i'\*(L'(\*(R'
X
X.fi
XAs mentioned earlier, if any list operator (print, etc.) or
Xany unary operator (chdir, etc.)
Xis followed by a left parenthesis as the next token on the same line,
Xthe operator and arguments within parentheses are taken to
Xbe of highest precedence, just like a normal function call.
XExamples:
X.nf
X
X	chdir $foo || die;\h'|3i'# (chdir $foo) || die
X	chdir($foo) || die;\h'|3i'# (chdir $foo) || die
X	chdir ($foo) || die;\h'|3i'# (chdir $foo) || die
X	chdir +($foo) || die;\h'|3i'# (chdir $foo) || die
X
Xbut, because * is higher precedence than ||:
X
X	chdir $foo * 20;\h'|3i'# chdir ($foo * 20)
X	chdir($foo) * 20;\h'|3i'# (chdir $foo) * 20
X	chdir ($foo) * 20;\h'|3i'# (chdir $foo) * 20
X	chdir +($foo) * 20;\h'|3i'# chdir ($foo * 20)
X
X	rand 10 * 20;\h'|3i'# rand (10 * 20)
X	rand(10) * 20;\h'|3i'# (rand 10) * 20
X	rand (10) * 20;\h'|3i'# (rand 10) * 20
X	rand +(10) * 20;\h'|3i'# rand (10 * 20)
X
X.fi
XIn the absence of parentheses,
Xthe precedence of list operators such as print, sort or chmod is
Xeither very high or very low depending on whether you look at the left
Xside of operator or the right side of it.
XFor example, in
X.nf
X
X	@ary = (1, 3, sort 4, 2);
X	print @ary;		# prints 1324
X
X.fi
Xthe commas on the right of the sort are evaluated before the sort, but
Xthe commas on the left are evaluated after.
XIn other words, list operators tend to gobble up all the arguments that
Xfollow them, and then act like a simple term with regard to the preceding
Xexpression.
XNote that you have to be careful with parens:
X.nf
X
X.ne 3
X	# These evaluate exit before doing the print:
X	print($foo, exit);	# Obviously not what you want.
X	print $foo, exit;	# Nor is this.
X
X.ne 4
X	# These do the print before evaluating exit:
X	(print $foo), exit;	# This is what you want.
X	print($foo), exit;	# Or this.
X	print ($foo), exit;	# Or even this.
X
XAlso note that
X
X	print ($foo & 255) + 1, "\en";
X
X.fi
Xprobably doesn't do what you expect at first glance.
X.Sh "Subroutines"
XA subroutine may be declared as follows:
X.nf
X
X    sub NAME BLOCK
X
X.fi
X.PP
XAny arguments passed to the routine come in as array @_,
Xthat is ($_[0], $_[1], .\|.\|.).
XThe array @_ is a local array, but its values are references to the
Xactual scalar parameters.
XThe return value of the subroutine is the value of the last expression
Xevaluated, and can be either an array value or a scalar value.
XAlternately, a return statement may be used to specify the returned value and
Xexit the subroutine.
XTo create local variables see the
X.I local
Xoperator.
X.PP
XA subroutine is called using the
X.I do
Xoperator or the & operator.
X.nf
X
X.ne 12
XExample:
X
X	sub MAX {
X		local($max) = pop(@_);
X		foreach $foo (@_) {
X			$max = $foo \|if \|$max < $foo;
X		}
X		$max;
X	}
X
X	.\|.\|.
X	$bestday = &MAX($mon,$tue,$wed,$thu,$fri);
X
X.ne 21
XExample:
X
X	# get a line, combining continuation lines
X	#  that start with whitespace
X	sub get_line {
X		$thisline = $lookahead;
X		line: while ($lookahead = <STDIN>) {
X			if ($lookahead \|=~ \|/\|^[ \^\e\|t]\|/\|) {
X				$thisline \|.= \|$lookahead;
X			}
X			else {
X				last line;
X			}
X		}
X		$thisline;
X	}
X
X	$lookahead = <STDIN>;	# get first line
X	while ($_ = do get_line(\|)) {
X		.\|.\|.
X	}
X
X.fi
X.nf
X.ne 6
XUse array assignment to a local list to name your formal arguments:
X
X	sub maybeset {
X		local($key, $value) = @_;
X		$foo{$key} = $value unless $foo{$key};
X	}
X
X.fi
XThis also has the effect of turning call-by-reference into call-by-value,
Xsince the assignment copies the values.
X.Sp
XSubroutines may be called recursively.
XIf a subroutine is called using the & form, the argument list is optional.
XIf omitted, no @_ array is set up for the subroutine; the @_ array at the
Xtime of the call is visible to subroutine instead.
X.nf
X
X	do foo(1,2,3);		# pass three arguments
X	&foo(1,2,3);		# the same
X
X	do foo();		# pass a null list
X	&foo();			# the same
X	&foo;			# pass no arguments\*(--more efficient
X
X.fi
X.Sh "Passing By Reference"
XSometimes you don't want to pass the value of an array to a subroutine but
Xrather the name of it, so that the subroutine can modify the global copy
Xof it rather than working with a local copy.
XIn perl you can refer to all the objects of a particular name by prefixing
Xthe name with a star: *foo.
XWhen evaluated, it produces a scalar value that represents all the objects
Xof that name, including any filehandle, format or subroutine.
XWhen assigned to within a local() operation, it causes the name mentioned
Xto refer to whatever * value was assigned to it.
XExample:
X.nf
X
X	sub doubleary {
X	    local(*someary) = @_;
X	    foreach $elem (@someary) {
X		$elem *= 2;
X	    }
X	}
X	do doubleary(*foo);
X	do doubleary(*bar);
X
X.fi
XAssignment to *name is currently recommended only inside a local().
XYou can actually assign to *name anywhere, but the previous referent of
X*name may be stranded forever.
XThis may or may not bother you.
X.Sp
!STUFFY!FUNK!
echo " "
echo "End of kit 8 (of 36)"
cat /dev/null >kit8isdone
run=''
config=''
for iskit in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36; do
    if test -f kit${iskit}isdone; then
	run="$run $iskit"
    else
	todo="$todo $iskit"
    fi
done
case $todo in
    '')
	echo "You have run all your kits.  Please read README and then type Configure."
	for combo in *:AA; do
	    if test -f "$combo"; then
		realfile=`basename $combo :AA`
		cat $realfile:[A-Z][A-Z] >$realfile
		rm -rf $realfile:[A-Z][A-Z]
	    fi
	done
	rm -rf kit*isdone
	chmod 755 Configure
	;;
    *)  echo "You have run$run."
	echo "You still need to run$todo."
	;;
esac
: Someone might mail this, so...
exit

exit 0 # Just in case...
-- 
Kent Landfield                   INTERNET: kent@sparky.IMD.Sterling.COM
Sterling Software, IMD           UUCP:     uunet!sparky!kent
Phone:    (402) 291-8300         FAX:      (402) 291-4362
Please send comp.sources.misc-related mail to kent@uunet.uu.net.