Info file: perl.info, -*-Text-*- produced by `texinfo-format-buffer' from file `perl.texinfo' using `texinfmt.el' version 2.30 of 18 May 1993. This file documents perl, Practical Extraction and Report Language, and was originally based on Larry Wall's unix-style man page for perl. GNU Texinfo version adapted by Jeff Kellem . Copyright (C) 1989, 1990, 1991, 1992, 1993 Larry Wall Texinfo version Copyright (C) 1990, 1991, 1993 Jeff Kellem Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies. Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided also that the sections entitled "GNU General Public License" and "Conditions for Using Perl" are included exactly as in the original, and provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions, except that the section entitled "GNU General Public License" and this permission notice may be included in translations approved by the Free Software Foundation instead of in the original English.  File: perl.info, Node: Syntax, Next: Compound Statements, Prev: Data Types, Up: Top Syntax ****** A *perl* script consists of a sequence of declarations and commands. The only things that need to be declared in *perl* are report formats and subroutines. See the sections below for more information on those declarations. All uninitialized user-created objects are assumed to start with a null or 0 value until they are defined by some explicit operation such as assignment. The sequence of commands is executed just once, unlike in `sed' and `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 `-n' or `-p' switch.) A declaration can be put anywhere a command can, but has no effect on the execution of the primary sequence of commands--declarations all take effect at compile time. Typically all the declarations are put at the beginning or the end of the script. *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.  File: perl.info, Node: Compound Statements, Next: Simple Statements, Prev: Syntax, Up: Top Compound Statements ******************* In *perl*, a sequence of commands may be treated as one command by enclosing it in curly brackets. We will call this a BLOCK. The following compound commands may be used to control flow: 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 foreach VAR (ARRAY) BLOCK LABEL BLOCK continue BLOCK Note that, unlike C and Pascal, these are defined in terms of BLOCKs, not statements. This means that the curly brackets are *required*---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: 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) ? 'hi mom' : die "Can't open $foo: $!"; # a bit exotic, that last one The `if' statement is straightforward. Since BLOCKs are always bounded by curly brackets, there is never any ambiguity about which `if' an `else' goes with. If you use `unless' in place of `if', the sense of the test is reversed. The `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 `next', `last', and `redo' (see below). If there is a `continue' BLOCK, it is always executed just before the conditional is about to be evaluated again, similarly to the third part of a `for' loop in C. Thus it can be used to increment a loop variable, even when the loop has been continued via the `next' statement (similar to the C `continue' statement). If the word `while' is replaced by the word `until', the sense of the test is reversed, but the conditional is still tested before the first iteration. In either the `if' or the `while' statement, you may replace `(EXPR)' with a BLOCK, and the conditional is true if the value of the last command in that block is true. The `for' loop works exactly like the corresponding `while' loop: for ($i = 1; $i < 10; $i++) { ... } is the same as $i = 1; while ($i < 10) { ... } continue { $i++; } The `foreach' loop iterates over a normal array value and sets the variable VAR to be each element of the array in turn. The variable is implicitly local to the loop, and regains its former value upon exiting the loop. The `foreach' keyword is actually identical to the `for' keyword, so you can use `foreach' for readability or `for' for brevity. If VAR is omitted, `$_' is set to each value. If ARRAY is an actual array (as opposed to an expression returning an array value), you can modify each element of the array by modifying VAR inside the loop. Examples: for (@ary) { s/foo/bar/; } foreach $elem (@elements) { $elem *= 2; } for ((10,9,8,7,6,5,4,3,2,1,'BOOM')) { print $_, "\n"; sleep(1); } for (1..15) { print "Merry Christmas\n"; } foreach $item (split(/:[\\\n:]*/, $ENV{'TERMCAP'})) { print "Item: $item\n"; } 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 `continue' block is optional. This construct is particularly nice for doing case structures. foo: { if (/^abc/) { $abc = 1; last foo; }; if (/^def/) { $def = 1; last foo; }; if (/^xyz/) { $xyz = 1; last foo; }; $nothing = 1; } There is no official switch statement in perl, because there are already several ways to write the equivalent. In addition to the above, you could write: foo: { $abc = 1, last foo if /^abc/; $def = 1, last foo if /^def/; $xyz = 1, last foo if /^xyz/; $nothing = 1; } or foo: { /^abc/ && do { $abc = 1; last foo; } /^def/ && do { $def = 1; last foo; } /^xyz/ && do { $xyz = 1; last foo; } $nothing = 1; } or foo: { /^abc/ && ($abc = 1, last foo); /^def/ && ($def = 1, last foo); /^xyz/ && ($xyz = 1, last foo); $nothing = 1; } or even if (/^abc/) { $abc = 1; } elsif (/^def/) { $def = 1; } elsif (/^xyz/) { $xyz = 1; } else {$nothing = 1;} As it happens, these are all optimized internally to a switch structure, so perl jumps directly to the desired statement, and you needn't worry about perl executing a lot of unnecessary statements when you have a string of 50 `elsif's, as long as you are testing the same simple scalar variable using `==', `eq', or pattern matching as above. (If you're curious as to whether the optimizer has done this for a particular case statement, you can use the `-D1024' switch to list the syntax tree before execution.)  File: perl.info, Node: Simple Statements, Next: Expressions, Prev: Compound Statements, Up: Top Simple Statements ***************** The only kind of simple statement is an expression evaluated for its side effects. Every simple statement must be terminated with a semicolon, unless it is the final statement in a block, in which case the semicolon is optional. (Semicolon is still encouraged there if the block takes up more than one line). Any simple statement may optionally be followed by a single modifier, just before the terminating semicolon. The possible modifiers are: if EXPR unless EXPR while EXPR until EXPR The `if' and `unless' modifiers have the expected semantics. The `while' and `until' modifiers also have the expected semantics (conditional evaluated first), except when applied to a do-BLOCK or a do-SUBROUTINE command, in which case the block executes once before the conditional is evaluated. This is so that you can write loops like: do { $_ = ; ... } until $_ eq ".\n"; (See the `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.)  File: perl.info, Node: Expressions, Next: Commands, Prev: Simple Statements, Up: Top Expressions *********** Since *perl* expressions work almost exactly like C expressions, only the differences will be mentioned here. Here's what *perl* has that C doesn't: ** The exponentiation operator. **= The exponentiation assignment operator. () The null list, used to initialize an array to null. . Concatenation of two strings. .= The concatenation assignment operator. eq String equality (`==' is numeric equality). For a mnemonic just think of `eq' as a string. (If you are used to the `awk' behavior of using `==' for either string or numeric equality based on the current form of the comparands, beware! You must be explicit here.) ne String inequality (`!=' is numeric inequality). lt String less than. gt String greater than. le String less than or equal. ge String greater than or equal. cmp String comparison, returning -1, 0, or 1. <=> Numeric comparison, returning -1, 0, or 1. =~ Certain operations search or modify the string `$_' 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 `$_'. 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. !~ Just like `=~' except the return value is negated. x The repetition operator. Returns a string consisting of the left operand repeated the number of times specified by the right operand. In an array context, if the left operand is a list in parens, it repeats the list. print '-' x 80; # print row of dashes print '-' x80; # illegal, x80 is identifier print "\t" x ($tab/8), ' ' x ($tab%8); # tab over @ones = (1) x 80; # an array of 80 1's @ones = (5) x @ones; # set all elements to 5 x= The repetition assignment operator. Only works on scalars. .. The range operator, which is really two different operators depending on the context. In an array context, returns an array of values counting (by ones) from the left value to the right value. This is useful for writing `for (1..10)' loops and for doing slice operations on arrays. In a scalar context, `..' returns a boolean value. The operator is bistable, like a flip-flop, and emulates the line-range (comma) operator of `sed', `awk', and various editors. Each `..' operator maintains its own boolean state. It is false as long as its left operand is false. Once the left operand is true, the range operator stays true until the right operand is true, *AFTER* which the range operator becomes false again. (It doesn't become false till the next time the range operator is evaluated. It can test the right operand and become false on the same evaluation it became true (as in `awk'), but it still returns true once. If you don't want it to test the right operand till the next evaluation (as in `sed'), use three dots (...) instead of two.) The right operand is not evaluated while the operator is in the "false" state, and the left operand is not evaluated while the operator is in the "true" state. 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 operand of scalar `..' is static, that operand is implicitly compared to the `$.' variable, the current line number. Examples: As a scalar operator: if (101 .. 200) { print; } # print 2nd hundred lines next line if (1 .. /^$/); # skip header lines s/^/> / if (/^$/ .. eof()); # quote body As an array operator: for (101 .. 200) { print; } # print $_ 100 times @foo = @foo[$[ .. $#foo]; # an expensive no-op @foo = @foo[$#foo-4 .. $#foo]; # slice last 5 items -x A file test. This unary operator takes one argument, either a filename or a filehandle, and tests the associated file to see if something is true about it. If the argument is omitted, tests `$_', except for `-t', which tests `STDIN'. It returns 1 for true and '' for false, or the undefined value if the file doesn't exist. Precedence is higher than logical and relational operators, but lower than arithmetic operators. The operator may be any of: -r File is readable by effective uid/gid. -w File is writable by effective uid/gid. -x File is executable by effective uid/gid. -o File is owned by effective uid. -R File is readable by real uid/gid. -W File is writable by real uid/gid. -X File is executable by real uid/gid. -O File is owned by real uid. -e File exists. -z File has zero size. -s File has non-zero size (returns size). -f File is a plain file. -d File is a directory. -l File is a symbolic link. -p File is a named pipe (FIFO). -S File is a socket. -b File is a block special file. -c File is a character special file. -u File has setuid bit set. -g File has setgid bit set. -k File has sticky bit set. -t Filehandle is opened to a tty. -T File is a text file. -B File is a binary file (opposite of -T). -M Age of file in days when script started. -A Same for access time. -C Same for inode change time. The interpretation of the file permission operators `-r', `-R', `-w', `-W', `-x' and `-X' is based solely on the mode of the file and the uids and gids of the user. There may be other reasons you can't actually read, write or execute the file. Also note that, for the superuser, `-r', `-R', `-w' and `-W' always return 1, and `-x' and `-X' return 1 if any execute bit is set in the mode. Scripts run by the superuser may thus need to do a `stat()' in order to determine the actual mode of the file, or temporarily set the uid to something else. Example: while (<>) { chop; next unless -f $_; # ignore specials ... } Note that `-s/a/b/' does not do a negated substitution. Saying `-exp($foo)' still works as expected, however--only single letters following a minus are interpreted as file tests. The `-T' and `-B' switches work as follows. The first block or so of the file is examined for odd characters such as strange control codes or metacharacters. If too many odd characters (>10%) are found, it's a `-B' file, otherwise it's a `-T' file. Also, any file containing null in the first block is considered a binary file. If `-T' or `-B' is used on a filehandle, the current stdio buffer is examined rather than the first block. Both `-T' and `-B' return TRUE on a null file, or a file at EOF when testing a filehandle. If any of the file tests (or either `stat' operator) are given the special filehandle consisting of a solitary underline `_', then the stat structure of the previous file test (or `stat' operator) is used, saving a system call. (This doesn't work with `-t', and you need to remember that `lstat' and `-l' will leave values in the stat structure for the symbolic link, not the real file.) Example: print "Can do.\n" if -r $a || -w _ || -x _; stat($filename); print "Readable\n" if -r _; print "Writable\n" if -w _; print "Executable\n" if -x _; print "Setuid\n" if -u _; print "Setgid\n" if -g _; print "Sticky\n" if -k _; print "Text\n" if -T _; print "Binary\n" if -B _; Here is what C has that *perl* doesn't: unary & Address-of operator. unary * Dereference-address operator. (TYPE) Type casting operator. Like C, *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: 'Now is the time for all' . "\n" . 'good men to come to.' and this all reduces to one string internally. The autoincrement operator has a little extra built-in magic to it. If you increment a variable that is numeric, or that has ever been used in a numeric context, you get a normal increment. If, however, the variable has only been used in string contexts since it was set, and has a value that is not null and matches the pattern `/^[a-zA-Z]*[0-9]*$/', the increment is done as a string, preserving each character within its range, with carry: print ++($foo = '99'); # prints `100' print ++($foo = 'a0'); # prints `a1' print ++($foo = 'Az'); # prints `Ba' print ++($foo = 'zz'); # prints `aaa' The autodecrement is not magical. The range operator (in an array context) makes use of the magical autoincrement algorithm if the minimum and maximum are strings. You can say @alphabet = ('A' .. 'Z'); to get all the letters of the alphabet, or $hexdigit = (0 .. 9, 'a' .. 'f')[$num & 15]; to get a hexadecimal digit, or @z2 = ('01' .. '31'); print @z2[$mday]; to get dates with leading zeros. (If the final value specified is not in the sequence that the magical increment would produce, the sequence goes until the next value would be longer than the final value specified.) The `||' and `&&' operators differ from C's in that, rather than returning 0 or 1, they return the last value evaluated. Thus, a portable way to find out the home directory might be: $home = $ENV{'HOME'} || $ENV{'LOGDIR'} || (getpwuid($<))[7] || die "You're homeless!\en"; 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. *Note Precedence::, for more info. For operators that can be used in either a scalar or array context, failure is generally indicated in a scalar context by returning the undefined value, and in an array context by returning the null list. Remember though that *THERE IS NO GENERAL RULE FOR CONVERTING A LIST INTO A SCALAR.* Each operator decides which sort of scalar it would be most appropriate to return. Some operators return the length of the list that would have been returned in an array context. Some operators return the first value in the list. Some operators return the last value in the list. Some operators return a count of successful operations. In general, they do what you want, unless you want consistency.  File: perl.info, Node: Commands, Next: Precedence, Prev: Expressions, Up: Top Commands ******** * Menu: * Math Functions:: Various trigonometric and math functions. * Structure Conversion:: How to convert binary structures. * String Functions:: Functions to interact with strings. * Array and List Functions:: Functions that manipulate arrays/lists. * File Operations:: Functions that operate on files. * Directory Reading Functions:: Functions for reading directories. :-) * Input/Output:: Printing and reading data. * Search and Replace Functions:: Pattern matching functions. * System Interaction:: A mix of functions dealing with the system. * Networking Functions:: Interprocess Communication Functions. * System V IPC:: System V IPC Functions. * Time Functions:: Time related functions. * DBM Functions:: Functions for accessing `dbm' files. * Flow Control Functions:: Functions related to flow control. * Perl Library Functions:: How to include perl libraries. * Subroutine Functions:: Functions related to user-defined subs. * Variable Functions:: Functions dealing with variables. (not already mentioned) * Miscellaneous Functions:: A catch-all for all other functions. ;-)  File: perl.info, Node: Math Functions, Next: Structure Conversion, Up: Commands Math Functions ============== atan2(Y,X) Returns the arctangent of Y/X in the range -PI to PI. cos(EXPR) cos EXPR cos Returns the cosine of EXPR (expressed in radians). If EXPR is omitted takes cosine of `$_'. exp(EXPR) exp EXPR exp Returns `e' to the power of EXPR. If EXPR is omitted, gives `exp($_)'. hex(EXPR) hex EXPR hex 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 `$_'. int(EXPR) int EXPR int Returns the integer portion of EXPR. If EXPR is omitted, uses `$_'. log(EXPR) log EXPR log Returns logarithm (base `e') of EXPR. If EXPR is omitted, returns log of `$_'. oct(EXPR) oct EXPR oct 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: $val = oct($val) if $val =~ /^0/; If EXPR is omitted, uses `$_'. sin(EXPR) sin EXPR sin Returns the sine of EXPR (expressed in radians). If EXPR is omitted, returns sine of `$_'. sqrt(EXPR) sqrt EXPR sqrt Return the square root of EXPR. If EXPR is omitted, returns square root of `$_'.  File: perl.info, Node: Structure Conversion, Next: String Functions, Prev: Math Functions, Up: Commands Structure Conversion ==================== pack(TEMPLATE,LIST) Takes an array or list of values and packs it into a binary structure, returning the string containing the structure. The TEMPLATE is a sequence of characters that give the order and type of values, as follows: A An ascii string, will be space padded. a An ascii string, will be null padded. c A signed char value. C An unsigned char value. s A signed short value. S An unsigned short value. i A signed integer value. I An unsigned integer value. l A signed long value. L An unsigned long value. n A short in `network' order. N A long in `network' order. f A single-precision float in the native format. d A double-precision float in the native format. p A pointer to a string. v A short in `VAX' (little-endian) order. V A long in `VAX' (little-endian) order. x A null byte. X Back up a byte. @ Null fill to absolute position. u A uuencoded string. b A bit string (ascending bit order, like vec()). B A bit string (descending bit order). h A hex string (low nybble first). H A hex string (high nybble first). Each letter may optionally be followed by a number which gives a repeat count. With all types except `a', `A', `b', `B', `h', and `H', the pack function will gobble up that many values from the LIST. A `*' for the repeat count means to use however many items are left. The `a' and `A' types gobble just one value, but pack it as a string of length count, padding with nulls or spaces as necessary. (When unpacking, `A' strips trailing spaces and nulls, but `a' does not.) Likewise, the `b' and `B' fields pack a string that many bits long. The `h' and `H' fields pack a string that many nybbles long. Real numbers (floats and doubles) are in the native machine format only; due to the multiplicity of floating formats around, and the lack of a standard "network" representation, no facility for interchange has been made. This means that packed floating point data written on one machine may not be readable on another - even if both use IEEE floating point arithmetic (as the endian-ness of the memory representation is not part of the IEEE spec). Note that perl uses doubles internally for all numeric calculation, and converting from double to float back to double will lose precision (i.e. `unpack("f", pack("f", $foo))' will not in general equal `$foo'). Examples: $foo = pack("cccc",65,66,67,68); # foo eq "ABCD" $foo = pack("c4",65,66,67,68); # same thing $foo = pack("ccxxcc",65,66,67,68); # foo eq "AB\0\0CD" $foo = pack("s2",1,2); # "\1\0\2\0" on little-endian # "\0\1\0\2" on big-endian $foo = pack("a4","abcd","x","y","z"); # "abcd" $foo = pack("aaaa","abcd","x","y","z"); # "axyz" $foo = pack("a14","abcdefg"); # "abcdefg\0\0\0\0\0\0\0" $foo = pack("i9pl", gmtime); # a real struct tm (on my system anyway) sub bintodec { unpack("N", pack("B32", substr("0" x 32 . shift, -32))); } The same template may generally also be used in the `unpack' function. unpack(TEMPLATE,EXPR) `unpack' does the reverse of `pack': it takes a string representing a structure and expands it out into an array value, returning the array value. (In a scalar context, it merely returns the first value produced.) The TEMPLATE has the same format as in the `pack' function. Here's a subroutine that does substring: sub substr { local($what,$where,$howmuch) = @_; unpack("x$where a$howmuch", $what); } and then there's sub ord { unpack("c",$_[0]); } In addition, you may prefix a field with a `%' to indicate that you want a -bit checksum of the items instead of the items themselves. Default is a 16-bit checksum. For example, the following computes the same number as the System V sum program: while (<>) { $checksum += unpack("%16C*", $_); } $checksum %= 65536;  File: perl.info, Node: String Functions, Next: Array and List Functions, Prev: Structure Conversion, Up: Commands String Functions ================ chop(LIST) chop(VARIABLE) chop VARIABLE chop 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/\n//' because it neither scans nor copies the string. If VARIABLE is omitted, chops `$_'. Example: while (<>) { chop; # avoid \n on last field @array = split(/:/); ... } You can actually chop anything that's an lvalue, including an assignment: chop($cwd = `pwd`); chop($answer = ); If you chop a list, each element is chopped. Only the value of the last chop is returned. crypt(PLAINTEXT,SALT) 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. index(STR,SUBSTR,POSITION) index(STR,SUBSTR) Returns the position of the first occurrence of SUBSTR in STR at or after POSITION. If POSITION is omitted, starts searching from the beginning of the string. The return value is 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. length(EXPR) length EXPR length Returns the length in characters of the value of EXPR. If EXPR is omitted, returns length of `$_'. rindex(STR,SUBSTR,POSITION) rindex(STR,SUBSTR) Works just like `index' except that it returns the position of the LAST occurrence of SUBSTR in STR. If POSITION is specified, returns the last occurrence at or before that position. substr(EXPR,OFFSET,LEN) substr(EXPR,OFFSET) Extracts a substring out of EXPR and returns it. First character is at offset 0, or whatever you've set `$[' to. If OFFSET is negative, starts that far from the end of the string. If LEN is omitted, returns everything to the end of the string. You can use the `substr()' function as an lvalue, in which case EXPR must be an lvalue. If you assign something shorter than LEN, the string will shrink, and if you assign something longer than LEN, the string will grow to accommodate it. To keep the string the same length you may need to pad or chop your value using `sprintf()'.  File: perl.info, Node: Array and List Functions, Next: File Operations, Prev: String Functions, Up: Commands Array and List Functions ======================== delete $ASSOC{KEY} 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. The following deletes all the values of an associative array: foreach $key (keys %ARRAY) { delete $ARRAY{$key}; } (But it would be faster to use the `reset' command. Saying `undef %ARRAY' is faster yet.) each(ASSOC_ARRAY) each ASSOC_ARRAY 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: while (($key,$value) = each %ENV) { print "$key=$value\n"; } See also `keys()' and `values()'. grep(EXPR,LIST) 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. In a scalar context, returns the number of times the expression was true. @foo = grep(!/^#/, @bar); # weed out comments Note that, since `$_' is a reference into the array value, it can be used to modify the elements of the array. While this is useful and supported, it can cause bizarre results if the LIST is not a named array. join(EXPR,LIST) join(EXPR,ARRAY) 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: $_ = join(':', $login,$passwd,$uid,$gid,$gcos,$home,$shell); See `split' function. keys(ASSOC_ARRAY) keys ASSOC_ARRAY 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: @keys = keys %ENV; @values = values %ENV; while ($#keys >= 0) { print pop(@keys), '=', pop(@values), "\n"; } or how about sorted by key: foreach $key (sort(keys %ENV)) { print $key, '=', $ENV{$key}, "\n"; } pop(ARRAY) pop ARRAY Pops and returns the last value of the array, shortening the array by 1. Has the same effect as: $tmp = $ARRAY[$#ARRAY--]; If there are no elements in the array, returns the undefined value. push(ARRAY,LIST) Treats ARRAY (`@' is optional) as a stack, and pushes the values of LIST onto the end of ARRAY. The length of ARRAY increases by the length of LIST. Has the same effect as: for $value (LIST) { $ARRAY[++$#ARRAY] = $value; } but is more efficient. reverse(LIST) reverse LIST In an array context, returns an array value consisting of the elements of LIST in the opposite order. In a scalar context, returns a string value consisting of the bytes of the first element of LIST in the opposite order. shift(ARRAY) shift ARRAY shift Shifts the first value of the array off and returns it, shortening the array by 1 and moving everything down. If there are no elements in the array, returns the undefined value. If ARRAY is omitted, shifts the `@ARGV' array in the main program, and the `@_' array in subroutines. (This is determined lexically.) 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. sort(SUBROUTINE LIST) sort(LIST) sort SUBROUTINE LIST sort BLOCK LIST sort LIST Sorts the LIST and returns the sorted array value. Nonexistent values of arrays are stripped out. If SUBROUTINE or BLOCK is omitted, sorts in standard string comparison order. If SUBROUTINE is specified, gives the name of a subroutine that returns an integer less than, equal to, or greater than 0, depending on how the elements of the array are to be ordered. (The `<=>' and `cmp' operators are extremely useful in such routines.) SUBROUTINE may be a scalar variable name, in which case the value provides the name of the subroutine to use. In place of a SUBROUTINE name, you can provide a BLOCK as an anonymous, in-line sort subroutine. In the interests of efficiency the normal calling code for subroutines is bypassed, with the following effects: the subroutine may not be a recursive subroutine, and the two elements to be compared are passed into the subroutine not via `@_' but as `$a' and `$b' (see example below). They are passed by reference so don't modify `$a' and `$b'. Examples: # sort lexically @articles = sort @files; # same thing, but with explicit sort routine @articles = sort { $a cmp $b } @files; # same thing in reversed order @articles = sort { $b cmp $a } @files; # sort numerically ascending @articles = sort { $a <=> $b } @files; # sort numerically descending @articles = sort { $b <=> $a } @files; # sort using explicit subroutine name sub byage { $age{$a} <=> $age{$b}; # presuming integers } @sortedclass = sort byage @class; sub reverse { $b cmp $a; } @harry = ('dog','cat','x','Cain','Abel'); @george = ('gone','chased','yz','Punished','Axed'); print sort @harry; # prints AbelCaincatdogx print sort reverse @harry; # prints xdogcatCainAbel print sort @george, 'to', @harry; # prints AbelAxedCainPunishedcatchaseddoggonetoxyz splice(ARRAY,OFFSET,LENGTH,LIST) splice(ARRAY,OFFSET,LENGTH) splice(ARRAY,OFFSET) Removes the elements designated by OFFSET and LENGTH from an array, and replaces them with the elements of LIST, if any. Returns the elements removed from the array. The array grows or shrinks as necessary. If LENGTH is omitted, removes everything from OFFSET onward. The following equivalencies hold (assuming `$[ == 0'): push(@a,$x,$y) splice(@a,$#x+1,0,$x,$y) pop(@a) splice(@a,-1) shift(@a) splice(@a,0,1) unshift(@a,$x,$y) splice(@a,0,0,$x,$y) $a[$x] = $y splice(@a,$x,1,$y); Example, assuming array lengths are passed before arrays: sub aeq { # compare two array values local(@a) = splice(@_,0,shift); local(@b) = splice(@_,0,shift); return 0 unless @a == @b; # same len? while (@a) { return 0 if pop(@a) ne pop(@b); } return 1; } if (&aeq($len,@foo[1..$len],0+@bar,@bar)) { ... } split(/PATTERN/,EXPR,LIMIT) split(/PATTERN/,EXPR) split(/PATTERN/) split Splits a string into an array of strings, and returns it. (If not in an array context, returns the number of fields found and splits into the `@_' array. (In an array context, you can force the split into `@_' by using `??' as the pattern delimiters, but it still returns the array value.)) If EXPR is omitted, splits the `$_' string. If PATTERN is also omitted, splits on whitespace (`/[\t\n]+/'). Anything matching PATTERN is taken to be a delimiter separating the fields. (Note that the delimiter may be longer than one character.) If LIMIT is specified, splits into no more than that many fields (though it may split into fewer). If LIMIT is unspecified, trailing null fields are stripped (which potential users of `pop()' would do well to remember). A pattern matching the null string (not to be confused with a null pattern `//', which is just one member of the set of patterns matching a null string) will split the value of EXPR into separate characters at each point it matches that way. For example: print join(':', split(/ */, 'hi there')); produces the output `h:i:t:h:e:r:e'. The LIMIT parameter can be used to partially split a line ($login, $passwd, $remainder) = split(/:/, $_, 3); (When assigning to a list, if LIMIT is omitted, perl supplies a LIMIT one larger than the number of variables in the list, to avoid unnecessary work. For the list above LIMIT would have been 4 by default. In time critical applications it behooves you not to split into more fields than you really need.) If the PATTERN contains parentheses, additional array elements are created from each matching substring in the delimiter. split(/([,-])/,"1-10,20"); produces the array value (1,'-',10,',',20) The pattern /PATTERN/ may be replaced with an expression to specify patterns that vary at runtime. (To do runtime compilation only once, use `/$variable/o'.) As a special case, specifying a 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. Example: open(passwd, '/etc/passwd'); while () { ($login, $passwd, $uid, $gid, $gcos, $home, $shell) = split(/:/); ... } (Note that `$shell' above will still have a newline on it. See `chop()'.) See also `join'. unshift(ARRAY,LIST) Does the opposite of a `shift'. Or the opposite of a `push', depending on how you look at it. Prepends list to the front of the array, and returns the number of elements in the new array. unshift(ARGV, '-e') unless $ARGV[0] =~ /^-/; values(ASSOC_ARRAY) values ASSOC_ARRAY 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 would produce on the same array. See also `keys()' and `each()'.  File: perl.info, Node: File Operations, Next: Directory Reading Functions, Prev: Array and List Functions, Up: Commands File Operations =============== chmod(LIST) chmod LIST 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. $cnt = chmod 0755, 'foo', 'bar'; chmod 0755, @executables; chown(LIST) chown LIST 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. $cnt = chown $uid, $gid, 'foo', 'bar'; chown $uid, $gid, @filenames; Here's an example that looks up non-numeric uids in the passwd file: print "User: "; $user = ; chop($user); print "Files: " $pattern = ; chop($pattern); open(pass, '/etc/passwd') || die "Can't open passwd: $!\n"; 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; } fcntl(FILEHANDLE,FUNCTION,SCALAR) Implements the `fcntl(2)' function. You'll probably have to say: require "fcntl.ph"; # probably /usr/local/lib/perl/fcntl.ph first to get the correct function definitions. If `fcntl.ph' doesn't exist or doesn't have the correct definitions you'll have to roll your own, based on your C header files such as `'. (There is a perl script called `h2ph' 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)'. fileno(FILEHANDLE) fileno FILEHANDLE 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. flock(FILEHANDLE,OPERATION) Calls `flock(2)' on FILEHANDLE. See manual page for `flock(2)' for definition of OPERATION. Returns true for success, false on failure. Will produce a fatal error if used on a machine that doesn't implement `flock(2)'. Here's a mailbox appender for BSD systems. $LOCK_SH = 1; $LOCK_EX = 2; $LOCK_NB = 4; $LOCK_UN = 8; sub lock { flock(MBOX,$LOCK_EX); # and, in case someone appended # while we were waiting... seek(MBOX, 0, 2); } sub unlock { flock(MBOX,$LOCK_UN); } open(MBOX, ">>/usr/spool/mail/$ENV{'USER'}") || die "Can't open mailbox: $!"; do lock(); print MBOX $msg,"\n\n"; do unlock(); link(OLDFILE,NEWFILE) Creates a new filename linked to the old filename. Returns 1 for success, 0 otherwise. lstat(FILEHANDLE) lstat FILEHANDLE lstat(EXPR) lstat SCALARVARIABLE 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. readlink(EXPR) readlink EXPR readlink Returns the value of a symbolic link, if symbolic links are implemented. If not, gives a fatal error. If there is some system error, returns the undefined value and sets `$!' (errno). If EXPR is omitted, uses `$_'. rename(OLDNAME,NEWNAME) Changes the name of a file. Returns 1 for success, 0 otherwise. Will not work across filesystem boundaries. stat(FILEHANDLE) stat FILEHANDLE stat(EXPR) stat SCALARVARIABLE Returns a 13-element array giving the statistics for a file, either the file opened via FILEHANDLE, or named by EXPR. Returns a null list if the `stat' fails. Typically used as follows: ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size, $atime,$mtime,$ctime,$blksize,$blocks) = stat($filename); If `stat' is passed the special filehandle consisting of an underline (`_'), no stat is done, but the current contents of the stat structure from the last stat or filetest are returned. Example: if (-x $file && (($d) = stat(_)) && $d < 0) { print "$file is executable NFS file\n"; } (This only works on machines for which the device number is negative under NFS.) symlink(OLDFILE,NEWFILE) 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 at run time. To check for that, use eval: $symlink_exists = (eval 'symlink("","");', $@ eq ''); truncate(FILEHANDLE,LENGTH) truncate(EXPR,LENGTH) Truncates the file opened on FILEHANDLE, or named by EXPR, to the specified length. Produces a fatal error if `truncate' isn't implemented on your system. unlink(LIST) unlink LIST unlink Deletes a list of files. If EXPR is not specified, deletes file specified by `$_'. Returns the number of files successfully deleted. $cnt = unlink 'a', 'b', 'c'; unlink @goners; unlink <*.bak>; Note: unlink will not delete directories unless you are superuser and the `-U' flag is supplied to *perl*. Even if these conditions are met, be warned that unlinking a directory can inflict damage on your filesystem. Use `rmdir' instead. utime(LIST) utime LIST Changes the access and modification times on each file of a list of files. The first two elements of the list must be the NUMERICAL access and modification times, in that order. Returns the number of files successfully changed. The inode modification time of each file is set to the current time. Example of a "touch" command: #!/usr/bin/perl $now = time; utime $now, $now, @ARGV;  File: perl.info, Node: Directory Reading Functions, Next: Input/Output, Prev: File Operations, Up: Commands Directory Reading Functions =========================== chdir(EXPR) chdir EXPR chdir 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 `die'. closedir(DIRHANDLE) closedir DIRHANDLE Closes a directory opened by `opendir()'. mkdir(FILENAME,MODE) 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). opendir(DIRHANDLE,EXPR) Opens a directory named EXPR for processing by `readdir()', `telldir()', `seekdir()', `rewinddir()' and `closedir()'. Returns true if successful. DIRHANDLEs have their own namespace separate from FILEHANDLEs. readdir(DIRHANDLE) readdir DIRHANDLE Returns the next directory entry for a directory opened by `opendir()'. If used in an array context, returns all the rest of the entries in the directory. If there are no more entries, returns an undefined value in a scalar context or a null list in an array context. rewinddir(DIRHANDLE) rewinddir DIRHANDLE Sets the current position to the beginning of the directory for the `readdir()' routine on DIRHANDLE. rmdir(FILENAME) rmdir FILENAME rmdir Deletes the directory specified by FILENAME if it is empty. If it succeeds it returns 1, otherwise it returns 0 and sets `$!' (errno). If FILENAME is omitted, uses `$_'. seekdir(DIRHANDLE,POS) Sets the current position for the `readdir()' routine on DIRHANDLE. POS must be a value returned by `telldir()'. Has the same caveats about possible directory compaction as the corresponding system library routine. telldir(DIRHANDLE) telldir DIRHANDLE Returns the current position of the `readdir()' routines on DIRHANDLE. Value may be given to `seekdir()' to access a particular location in a directory. Has the same caveats about possible directory compaction as the corresponding system library routine.