''' Beginning of part 2 ''' $Header: perl.man.2,v 3.0 89/10/18 15:21:37 lwall Locked $ ''' ''' $Log: perl.man.2,v $ ''' Revision 3.0 89/10/18 15:21:37 lwall ''' 3.0 baseline ''' ''' .PP Along with the literals and variables mentioned earlier, the operations in the following section can serve as terms in an expression. Some of these operations take a LIST as an argument. Such a list can consist of any combination of scalar arguments or array values; the array values will be included in the list as if each individual element were interpolated at that point in the list, forming a longer single-dimensional array value. Elements of the LIST should be separated by commas. If an operation is listed both with and without parentheses around its arguments, it means you can either use it as a unary operator or as a function call. To use it as a function call, the next token on the same line must be a left parenthesis. (There may be intervening white space.) Such a function then has highest precedence, as you would expect from a function. If any token other than a left parenthesis follows, then it is a unary operator, with a precedence depending only on whether it is a LIST operator or not. LIST operators have lowest precedence. All other unary operators have a precedence greater than relational operators but less than arithmetic operators. See the section on Precedence. .Ip "/PATTERN/" 8 4 See m/PATTERN/. .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 occurrence of something in each file of a set of files, for instance. Only ?? patterns local to the current package are reset. .Ip "accept(NEWSOCKET,GENERICSOCKET)" 8 2 Does the same thing that the accept system call does. Returns true if it succeeded, false otherwise. See example in section on Interprocess Communication. .Ip "atan2(X,Y)" 8 2 Returns the arctangent of X/Y in the range .if t \-\(*p to \(*p. .if n \-PI to PI. .Ip "bind(SOCKET,NAME)" 8 2 Does the same thing that the bind system call does. Returns true if it succeeded, false otherwise. NAME should be a packed address of the proper type for the socket. See example in section on Interprocess Communication. .Ip "chdir(EXPR)" 8 2 .Ip "chdir EXPR" 8 2 Changes the working directory to EXPR, if possible. If EXPR is omitted, changes to home directory. Returns 1 upon success, 0 otherwise. See example under .IR die . .Ip "chmod(LIST)" 8 2 .Ip "chmod LIST" 8 2 Changes the permissions of a list of files. The first element of the list must be the numerical mode. Returns the number of files successfully changed. .nf .ne 2 $cnt = chmod 0755, \'foo\', \'bar\'; chmod 0755, @executables; .fi .Ip "chop(LIST)" 8 7 .Ip "chop(VARIABLE)" 8 .Ip "chop VARIABLE" 8 .Ip "chop" 8 Chops off the last character of a string and returns the character chopped. 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 You can actually chop anything that's an lvalue, including an assignment: .nf chop($cwd = \`pwd\`); chop($answer = ); .fi If you chop a list, each element is chopped. Only the value of the last chop is returned. .Ip "chown(LIST)" 8 2 .Ip "chown LIST" 8 2 Changes the owner (and group) of a list of files. The first two elements of the list must be the NUMERICAL uid and gid, in that order. Returns the number of files successfully changed. .nf .ne 2 $cnt = chown $uid, $gid, \'foo\', \'bar\'; chown $uid, $gid, @filenames; .fi .ne 23 Here's an example of looking up non-numeric uids: .nf print "User: "; $user = ; chop($user); print "Files: " $pattern = ; chop($pattern); open(pass, \'/etc/passwd\') || die "Can't open passwd: $!\en"; while () { ($login,$pass,$uid,$gid) = split(/:/); $uid{$login} = $uid; $gid{$login} = $gid; } @ary = <$pattern>; # get filenames if ($uid{$user} eq \'\') { die "$user not in passwd file"; } else { chown $uid{$user}, $gid{$user}, @ary; } .fi .Ip "chroot(FILENAME)" 8 5 .Ip "chroot FILENAME" 8 Does the same as the system call of that name. If you don't know what it does, don't worry about it. If FILENAME is omitted, does chroot to $_. .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. Closing a pipe explicitly also puts the status value of the command into $?. 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 FILEHANDLE may be an expression whose value gives the real filehandle name. .Ip "closedir(DIRHANDLE)" 8 5 .Ip "closedir DIRHANDLE" 8 Closes a directory opened by opendir(). .Ip "connect(SOCKET,NAME)" 8 2 Does the same thing that the connect system call does. Returns true if it succeeded, false otherwise. NAME should be a package address of the proper type for the socket. See example in section on Interprocess Communication. .Ip "cos(EXPR)" 8 6 .Ip "cos EXPR" 8 6 Returns the cosine of EXPR (expressed in radians). If EXPR is omitted takes cosine of $_. .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 "dbmclose(ASSOC_ARRAY)" 8 6 .Ip "dbmclose ASSOC_ARRAY" 8 Breaks the binding between a dbm file and an associative array. The values remaining in the associative array are meaningless unless you happen to want to know what was in the cache for the dbm file. This function is only useful if you have ndbm. .Ip "dbmopen(ASSOC,DBNAME,MODE)" 8 6 This binds a dbm or ndbm file to an associative array. ASSOC is the name of the associative array. (Unlike normal open, the first argument is NOT a filehandle, even though it looks like one). DBNAME is the name of the database (without the .dir or .pag extension). If the database does not exist, it is created with protection specified by MODE (as modified by the umask). If your system only supports the older dbm functions, you may only have one dbmopen in your program. If your system has neither dbm nor ndbm, calling dbmopen produces a fatal error. .Sp Values assigned to the associative array prior to the dbmopen are lost. A certain number of values from the dbm file are cached in memory. By default this number is 64, but you can increase it by preallocating that number of garbage entries in the associative array before the dbmopen. You can flush the cache if necessary with the reset command. .Sp If you don't have write access to the dbm file, you can only read associative array variables, not set them. If you want to test whether you can write, either use file tests or try setting a dummy array entry inside an eval, which will trap the error. .Sp Note that functions such as keys() and values() may return huge array values when used on large dbm files. You may prefer to use the each() function to iterate over large dbm files. Example: .nf .ne 6 # print out history file offsets dbmopen(HIST,'/usr/lib/news/history',0666); while (($key,$val) = each %HIST) { print $key, ' = ', unpack('L',$val), "\en"; } dbmclose(HIST); .fi .Ip "defined(EXPR)" 8 6 .Ip "defined EXPR" 8 Returns a boolean value saying whether the lvalue EXPR has a real value or not. Many operations return the undefined value under exceptional conditions, such as end of file, uninitialized variable, system error and such. This function allows you to distinguish between an undefined null string and a defined null string with operations that might return a real null string, in particular referencing elements of an array. You may also check to see if arrays or subroutines exist. Use on predefined variables is not guaranteed to produce intuitive results. Examples: .nf .ne 7 print if defined $switch{'D'}; print "$val\en" while defined($val = pop(@ary)); die "Can't readlink $sym: $!" unless defined($value = readlink $sym); eval '@foo = ()' if defined(@foo); die "No XYZ package defined" unless defined %_XYZ; sub foo { defined &bar ? &bar(@_) : die "No bar"; } .fi See also undef. .Ip "delete $ASSOC{KEY}" 8 6 Deletes the specified value from the specified associative array. Returns the deleted value, or the undefined value if nothing was deleted. Deleting from $ENV{} modifies the environment. Deleting from an array bound to a dbm file deletes the entry from the dbm file. .Sp The following deletes all the values of an associative array: .nf .ne 3 foreach $key (keys %ARRAY) { delete $ARRAY{$key}; } .fi (But it would be faster to use the .I reset command. Saying undef %ARRAY is faster yet.) .Ip "die(LIST)" 8 .Ip "die LIST" 8 Prints the value of LIST to .I STDERR and exits with the current value of $! (errno). If $! is 0, exits with the value of ($? >> 8) (\`command\` status). If ($? >> 8) is 0, exits with 255. Equivalent examples: .nf .ne 3 die "Can't cd to spool: $!\en" unless chdir \'/usr/spool/news\'; chdir \'/usr/spool/news\' || die "Can't cd to spool: $!\en" .fi .Sp If the value of EXPR does not end in a newline, the current script line number and input line number (if any) are also printed, and a newline is supplied. Hint: sometimes appending \*(L", stopped\*(R" to your message will cause it to make better sense when the string \*(L"at foo line 123\*(R" is appended. Suppose you are running script \*(L"canasta\*(R". .nf .ne 7 die "/etc/games is no good"; die "/etc/games is no good, stopped"; produce, respectively /etc/games is no good at canasta line 123. /etc/games is no good, stopped at canasta line 123. .fi 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. If there is no subroutine by that name, produces a fatal error. (You may use the \*(L"defined\*(R" operator to determine if a subroutine exists.) If you pass arrays as part of LIST you may wish to pass the length of the array in front of each array. (See the section on subroutines later on.) SUBROUTINE may be a scalar variable, in which case the variable contains the name of the subroutine to execute. The parentheses are required to avoid confusion with the \*(L"do EXPR\*(R" form. .Sp As an alternate form, you may call a subroutine by prefixing the name with an ampersand: &foo(@args). If you aren't passing any arguments, you don't have to use parentheses. If you omit the parentheses, no @_ array is passed to the subroutine. The & form is also used to specify subroutines to the defined and undef operators. .Ip "do EXPR" 8 3 Uses the value of EXPR as a filename and executes the contents of the file as a .I perl script. Its primary use is to include subroutines from a .I perl subroutine library. .nf do \'stat.pl\'; is just like eval \`cat stat.pl\`; .fi except that it's more efficient, more concise, keeps track of the current filename for error messages, and searches all the .B \-I libraries if the file isn't in the current directory (see also the @INC array in Predefined Names). It's the same, however, in that it does reparse the file every time you call it, so if you are going to use the file inside a loop you might prefer to use \-P and #include, at the expense of a little more startup time. (The main problem with #include is that cpp doesn't grok # comments\*(--a workaround is to use \*(L";#\*(R" for standalone comments.) Note that the following are NOT equivalent: .nf .ne 2 do $foo; # eval a file do $foo(); # call a subroutine .fi .Ip "dump LABEL" 8 6 This causes an immediate core dump. Primarily this is so that you can use the undump program to turn your core dump into an executable binary after having initialized all your variables at the beginning of the program. When the new binary is executed it will begin by executing a "goto LABEL" (with all the restrictions that goto suffers). Think of it as a goto with an intervening core dump and reincarnation. If LABEL is omitted, restarts the program from the top. WARNING: any files opened at the time of the dump will NOT be open any more when the program is reincarnated, with possible resulting confusion on the part of perl. See also \-u. .Sp Example: .nf .ne 16 #!/usr/bin/perl do 'getopt.pl'; do 'stat.pl'; %days = ( 'Sun',1, 'Mon',2, 'Tue',3, 'Wed',4, 'Thu',5, 'Fri',6, 'Sat',7); dump QUICKSTART if $ARGV[0] eq '-d'; QUICKSTART: do Getopt('f'); .fi .Ip "each(ASSOC_ARRAY)" 8 6 .Ip "each ASSOC_ARRAY" 8 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 must not modify the array while iterating over it. There is a single iterator for each associative array, shared by all each(), keys() and values() function calls in the program. 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 .Ip "eof" 8 Returns 1 if the next read on FILEHANDLE will return end of file, or if FILEHANDLE is not open. FILEHANDLE may be an expression whose value gives the real filehandle name. An eof without an argument returns the eof status for the last file read. Empty parentheses () may be used to indicate the pseudo file formed of the files listed on the command line, i.e. eof() is reasonable to use inside a while (<>) loop to detect the end of only the last file. Use eof(ARGV) or eof without the parentheses to test EACH file in a while (<>) loop. Examples: .nf .ne 7 # insert dashes just before last line of last file while (<>) { if (eof()) { print "\-\|\-\|\-\|\-\|\-\|\-\|\-\|\-\|\-\|\-\|\-\|\-\|\-\|\-\en"; } print; } .ne 7 # reset line numbering on each input file while (<>) { print "$.\et$_"; if (eof) { # Not eof(). close(ARGV); } } .fi .Ip "eval(EXPR)" 8 6 .Ip "eval EXPR" 8 6 EXPR is parsed and executed as if it were a little .I perl program. It is executed in the context of the current .I 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 $_. The final semicolon, if any, may be omitted from the expression. .Sp Note that, since eval traps otherwise-fatal errors, it is useful for determining whether a particular feature (such as dbmopen or symlink) is implemented. .Ip "exec(LIST)" 8 8 .Ip "exec LIST" 8 6 If there is more than one argument in LIST, or if LIST is an array with more than one value, calls execvp() with the arguments in LIST. If there is only one scalar argument, the argument is checked for shell metacharacters. If there are any, the entire argument is passed to \*(L"/bin/sh \-c\*(R" 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. Examples: .nf exec \'/bin/echo\', \'Your arguments are: \', @ARGV; exec "sort $outfile | uniq"; .fi .Sp If you don't really want to execute the first argument, but want to lie to the program you are executing about its own name, you can specify the program you actually want to run by assigning that to a variable and putting the name of the variable in front of the LIST without a comma. (This always forces interpretation of the LIST as a multi-valued list, even if there is only a single scalar in the list.) Example: .nf .ne 2 $shell = '/bin/csh'; exec $shell '-sh'; # pretend it's a login shell .fi .Ip "exit(EXPR)" 8 6 .Ip "exit EXPR" 8 Evaluates EXPR and exits immediately with that value. Example: .nf .ne 2 $ans = ; exit 0 \|if \|$ans \|=~ \|/\|^[Xx]\|/\|; .fi See also .IR die . If EXPR is omitted, exits with 0 status. .Ip "exp(EXPR)" 8 3 .Ip "exp EXPR" 8 Returns .I e to the power of EXPR. If EXPR is omitted, gives exp($_). .Ip "fcntl(FILEHANDLE,FUNCTION,SCALAR)" 8 4 Implements the fcntl(2) function. You'll probably have to say .nf do "fcntl.h"; # probably /usr/local/lib/perl/fcntl.h .fi first to get the correct function definitions. If fcntl.h doesn't exist or doesn't have the correct definitions you'll have to roll your own, based on your C header files such as . (There is a perl script called makelib that comes with the perl kit which may help you in this.) Argument processing and value return works just like ioctl below. Note that fcntl will produce a fatal error if used on a machine that doesn't implement fcntl(2). .Ip "fileno(FILEHANDLE)" 8 4 Returns the file descriptor for a filehandle. Useful for constructing bitmaps for select(). If FILEHANDLE is an expression, the value is taken as the name of the filehandle. .Ip "flock(FILEHANDLE,OPERATION)" 8 4 Calls flock(2) on FILEHANDLE. See manual page for flock(2) for definition of OPERATION. Will produce a fatal error if used on a machine that doesn't implement flock(2). Here's a mailbox appender for BSD systems. .nf .ne 20 $LOCK_SH = 1; $LOCK_EX = 2; $LOCK_NB = 4; $LOCK_UN = 8; sub lock { flock(MBOX,$LOCK_EX); # and, in case someone appended # while we were waiting... seek(MBOX, 0, 2); } sub unlock { flock(MBOX,$LOCK_UN); } open(MBOX, ">>/usr/spool/mail/$USER") || die "Can't open mailbox: $!"; do lock(); print MBOX $msg,"\en\en"; do unlock(); .fi .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 "getc(FILEHANDLE)" 8 4 .Ip "getc FILEHANDLE" 8 .Ip "getc" 8 Returns the next character from the input file attached to FILEHANDLE, or a null string at EOF. If FILEHANDLE is omitted, reads from STDIN. .Ip "getlogin" 8 3 Returns the current login from /etc/utmp, if any. If null, use getpwuid. ($login = getlogin) || (($login) = getpwuid($<)); .Ip "getpeername(SOCKET)" 8 3 Returns the packed sockaddr address of other end of the SOCKET connection. .nf .ne 4 # An internet sockaddr $sockaddr = 'S n a4 x8'; $hersockaddr = getpeername(S); ($family, $port, $heraddr) = unpack($sockaddr,$hersockaddr); .fi .Ip "getpgrp(PID)" 8 4 .Ip "getpgrp PID" 8 Returns the current process group for the specified PID, 0 for the current process. Will produce a fatal error if used on a machine that doesn't implement getpgrp(2). If EXPR is omitted, returns process group of current process. .Ip "getppid" 8 4 Returns the process id of the parent process. .Ip "getpriority(WHICH,WHO)" 8 4 Returns the current priority for a process, a process group, or a user. (See getpriority(2).) Will produce a fatal error if used on a machine that doesn't implement getpriority(2). .Ip "getpwnam(NAME)" 8 .Ip "getgrnam(NAME)" 8 .Ip "gethostbyname(NAME)" 8 .Ip "getnetbyname(NAME)" 8 .Ip "getprotobyname(NAME)" 8 .Ip "getpwuid(UID)" 8 .Ip "getgrgid(GID)" 8 .Ip "getservbyname(NAME,PROTO)" 8 .Ip "gethostbyaddr(ADDR,ADDRTYPE)" 8 .Ip "getnetbyaddr(ADDR,ADDRTYPE)" 8 .Ip "getprotobynumber(NUMBER)" 8 .Ip "getservbyport(PORT,PROTO)" 8 .Ip "getpwent()" 8 .Ip "getgrent()" 8 .Ip "gethostent()" 8 .Ip "getnetent()" 8 .Ip "getprotoent()" 8 .Ip "getservent()" 8 .Ip "setpwent()" 8 .Ip "setgrent()" 8 .Ip "sethostent(STAYOPEN)" 8 .Ip "setnetent(STAYOPEN)" 8 .Ip "setprotoent(STAYOPEN)" 8 .Ip "setservent(STAYOPEN)" 8 .Ip "endpwent()" 8 .Ip "endgrent()" 8 .Ip "endhostent()" 8 .Ip "endnetent()" 8 .Ip "endprotoent()" 8 .Ip "endservent()" 8 These routines perform the same functions as their counterparts in the system library. The return values from the various get routines are as follows: .nf ($name,$passwd,$uid,$gid, $quota,$comment,$gcos,$dir,$shell) = getpw.\|.\|. ($name,$passwd,$gid,$members) = getgr.\|.\|. ($name,$aliases,$addrtype,$length,@addrs) = gethost.\|.\|. ($name,$aliases,$addrtype,$net) = getnet.\|.\|. ($name,$aliases,$proto) = getproto.\|.\|. ($name,$aliases,$port,$proto) = getserv.\|.\|. .fi The $members value returned by getgr.\|.\|. is a space separated list of the login names of the members of the group. .Sp The @addrs value returned by the gethost.\|.\|. functions is a list of the raw addresses returned by the corresponding system library call. In the Internet domain, each address is four bytes long and you can unpack it by saying something like: .nf ($a,$b,$c,$d) = unpack('C4',$addr[0]); .fi .Ip "getsockname(SOCKET)" 8 3 Returns the packed sockaddr address of this end of the SOCKET connection. .nf .ne 4 # An internet sockaddr $sockaddr = 'S n a4 x8'; $mysockaddr = getsockname(S); ($family, $port, $myaddr) = unpack($sockaddr,$mysockaddr); .fi .Ip "getsockopt(SOCKET,LEVEL,OPTNAME)" 8 3 Returns the socket option requested, or undefined if there is an error. .Ip "gmtime(EXPR)" 8 4 .Ip "gmtime EXPR" 8 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, and come straight out of a struct tm. In particular this means that $mon has the range 0.\|.11 and $wday has the range 0.\|.6. If EXPR is omitted, does gmtime(time). .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 .IR sed -to- perl translator easier. I may change its semantics at any time, consistent with support for translated .I sed scripts. Use it at your own risk. Better yet, don't use it at all. .Ip "grep(EXPR,LIST)" 8 4 Evaluates EXPR for each element of LIST (locally setting $_ to each element) and returns the array value consisting of those elements for which the expression evaluated to true. .nf @foo = grep(!/^#/, @bar); # weed out comments .fi .Ip "hex(EXPR)" 8 4 .Ip "hex EXPR" 8 Returns the decimal value of EXPR interpreted as an hex string. (To interpret strings that might start with 0 or 0x see oct().) If EXPR is omitted, uses $_. .Ip "ioctl(FILEHANDLE,FUNCTION,SCALAR)" 8 4 Implements the ioctl(2) function. You'll probably have to say .nf do "ioctl.h"; # probably /usr/local/lib/perl/ioctl.h .fi first to get the correct function definitions. If ioctl.h doesn't exist or doesn't have the correct definitions you'll have to roll your own, based on your C header files such as . (There is a perl script called makelib that comes with the perl kit which may help you in this.) SCALAR will be read and/or written depending on the FUNCTION\*(--a pointer to the string value of SCALAR will be passed as the third argument of the actual ioctl call. (If SCALAR has no string value but does have a numeric value, that value will be passed rather than a pointer to the string value. To guarantee this to be true, add a 0 to the scalar before using it.) The pack() and unpack() functions are useful for manipulating the values of structures used by ioctl(). The following example sets the erase character to DEL. .nf .ne 9 do 'ioctl.h'; $sgttyb_t = "ccccs"; # 4 chars and a short if (ioctl(STDIN,$TIOCGETP,$sgttyb)) { @ary = unpack($sgttyb_t,$sgttyb); $ary[2] = 127; $sgttyb = pack($sgttyb_t,@ary); ioctl(STDIN,$TIOCSETP,$sgttyb) || die "Can't ioctl: $!"; } .fi The return value of ioctl (and fcntl) is as follows: .nf .ne 4 if OS returns:\h'|3i'perl returns: -1\h'|3i' undefined value 0\h'|3i' string "0 but true" anything else\h'|3i' that number .fi Thus perl returns true on success and false on failure, yet you can still easily determine the actual value returned by the operating system: .nf ($retval = ioctl(...)) || ($retval = -1); printf "System returned %d\en", $retval; .fi .Ip "index(STR,SUBSTR)" 8 4 Returns the position of the first occurrence 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 4 .Ip "int EXPR" 8 Returns the integer portion of EXPR. If EXPR is omitted, uses $_. .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 .Ip "keys ASSOC_ARRAY" 8 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"; } or how about sorted by key: .ne 3 foreach $key (sort(keys %ENV)) { print $key, \'=\', $ENV{$key}, "\en"; } .fi .Ip "kill(LIST)" 8 8 .Ip "kill LIST" 8 2 Sends a signal to a list of processes. The first element of the list must be the signal to send. Returns the number of processes successfully signaled. .nf $cnt = kill 1, $child1, $child2; kill 9, @goners; .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.) You may use a signal name in quotes. .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 () { last line if /\|^$/; # exit when done with header .\|.\|. } .fi .Ip "length(EXPR)" 8 4 .Ip "length EXPR" 8 Returns the length in characters of the value of EXPR. If EXPR is omitted, returns length of $_. .Ip "link(OLDFILE,NEWFILE)" 8 2 Creates a new filename linked to the old filename. Returns 1 for success, 0 otherwise. .Ip "listen(SOCKET,QUEUESIZE)" 8 2 Does the same thing that the listen system call does. Returns true if it succeeded, false otherwise. See example in section on Interprocess Communication. .Ip "local(LIST)" 8 4 Declares the listed variables to be local to the enclosing block, subroutine, eval or \*(L"do\*(R". All the listed elements must be legal lvalues. This operator works by saving the current values of those variables in LIST on a hidden stack and restoring them upon exiting the block, subroutine or eval. This means that called subroutines can also reference the local variable, but not the global one. The LIST may be assigned to if desired, which allows you to initialize your local variables. (If no initializer is given, all scalars are initialized to the null string and all arrays and associative arrays to the null array.) Commonly this is used to name the parameters to a subroutine. Examples: .nf .ne 13 sub RANGEVAL { local($min, $max, $thunk) = @_; local($result) = \'\'; local($i); # Presumably $thunk makes reference to $i for ($i = $min; $i < $max; $i++) { $result .= eval $thunk; } $result; } .ne 6 if ($sw eq \'-v\') { # init local array with global array local(@ARGV) = @ARGV; unshift(\'echo\',@ARGV); system @ARGV; } # @ARGV restored .ne 6 # temporarily add to digits associative array if ($base12) { # (NOTE: not claiming this is efficient!) local(%digits) = (%digits,'t',10,'e',11); do parse_num(); } .fi Note that local() is a run-time command, and so gets executed every time through a loop, using up more stack storage each time until it's all released at once when the loop is exited. .Ip "localtime(EXPR)" 8 4 .Ip "localtime EXPR" 8 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, and come straight out of a struct tm. In particular this means that $mon has the range 0.\|.11 and $wday has the range 0.\|.6. If EXPR is omitted, does localtime(time). .Ip "log(EXPR)" 8 4 .Ip "log EXPR" 8 Returns logarithm (base .IR e ) of EXPR. If EXPR is omitted, returns log of $_. .Ip "lstat(FILEHANDLE)" 8 6 .Ip "lstat FILEHANDLE" 8 .Ip "lstat(EXPR)" 8 Does the same thing as the stat() function, but stats a symbolic link instead of the file the symbolic link points to. If symbolic links are unimplemented on your system, a normal stat is done. .Ip "m/PATTERN/io" 8 4 .Ip "/PATTERN/io" 8 Searches a string for a pattern match, 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 / is the delimiter then the initial \*(L'm\*(R' is optional. With the \*(L'm\*(R' you can use any pair of characters as delimiters. This is particularly useful for matching Unix path names that contain \*(L'/\*(R'. If the final delimiter is followed by the optional letter \*(L'i\*(R', the matching is done in a case-insensitive manner. PATTERN may contain references to scalar variables, which will be interpolated (and the pattern recompiled) every time the pattern search is evaluated. If you want such a pattern to be compiled only once, add an \*(L"o\*(R" after the trailing delimiter. This avoids expensive run-time recompilations, and is useful when the value you are interpolating won't change over the life of the script. .Sp If used in a context that requires an array value, a pattern match returns an array consisting of the subexpressions matched by the parentheses in the pattern, i.e. ($1, $2, $3.\|.\|.). It does NOT actually set $1, $2, etc. in this case, nor does it set $+, $`, $& or $'. If the match fails, a null array is returned. .Sp Examples: .nf .ne 4 open(tty, \'/dev/tty\'); \|=~ \|/\|^y\|/i \|&& \|do foo(\|); # do foo if desired if (/Version: \|*\|([0\-9.]*\|)\|/\|) { $version = $1; } next if m#^/usr/spool/uucp#; .ne 5 # poor man's grep $arg = shift; while (<>) { print if /$arg/o; # compile only once } if (($F1, $F2, $Etc) = ($foo =~ /^(\eS+)\es+(\eS+)\es*(.*)/)) .fi This last example splits $foo into the first two words and the remainder of the line, and assigns those three fields to $F1, $F2 and $Etc. The conditional is true if any variables were assigned, i.e. if the pattern matched. .Ip "mkdir(FILENAME,MODE)" 8 3 Creates the directory specified by FILENAME, with permissions specified by MODE (as modified by umask). If it succeeds it returns 1, otherwise it returns 0 and sets $! (errno).