home *** CD-ROM | disk | FTP | other *** search
GNU Info File | 1994-07-08 | 38.2 KB | 981 lines |
- This is Info file perl.info, produced by Makeinfo-1.55 from the input
- file perltexi.
-
- 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
- <composer@Beyond.Dreams.ORG>.
-
- 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: 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 = <STDIN>);
-
- 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 (<passwd>) {
- ($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 = <STDIN>;
- chop($user);
- print "Files: "
- $pattern = <STDIN>;
- chop($pattern);
- open(pass, '/etc/passwd') || die "Can't open passwd: $!\n";
- while (<pass>) {
- ($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
- `<sys/fcntl.h>'. (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.
-
- File: perl.info, Node: Input/Output, Next: Search and Replace Functions, Prev: Directory Reading Functions, Up: Commands
-
- Input/Output
- ============
-
- binmode(FILEHANDLE)
- binmode FILEHANDLE
- Arranges for the file to be read in *binary* mode in operating
- systems that distinguish between binary and text files. Files
- that are not read in binary mode have CR LF sequences translated
- to LF on input and LF translated to CR LF on output. `binmode'
- has no effect under Unix. If FILEHANDLE is an expression, the
- value is taken as the name of the filehandle.
-
- close(FILEHANDLE)
- close FILEHANDLE
- 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
- `open'.) However, an explicit close on an input file resets the
- line counter (`$.'), while the implicit close done by `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:
-
- 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
-
- FILEHANDLE may be an expression whose value gives the real
- filehandle name.
-
- eof(FILEHANDLE)
- eof()
- eof
- 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. (Note that this
- function actually reads a character and the `ungetc''s it, so it is
- not very useful in an interactive context.) 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:
-
- # insert dashes just before last line of last file
- while (<>) {
- if (eof()) {
- print "--------------\n";
- }
- print;
- }
-
- # reset line numbering on each input file
- while (<>) {
- print "$.\t$_";
- if (eof) { # Not eof().
- close(ARGV);
- }
- }
-
- getc(FILEHANDLE)
- getc FILEHANDLE
- getc
- Returns the next character from the input file attached to
- FILEHANDLE, or a null string at EOF. If FILEHANDLE is omitted,
- reads from STDIN.
-
- open(FILEHANDLE,EXPR)
- open(FILEHANDLE)
- open FILEHANDLE
- Opens the file whose filename is given by EXPR, and associates it
- with FILEHANDLE. If FILEHANDLE is an expression, its value is
- used as the name of the real filehandle wanted. If EXPR is
- omitted, the scalar variable of the same name as the FILEHANDLE
- contains the filename. If the filename begins with `<' or
- nothing, the file is opened for input. If the filename begins
- with `>', the file is opened for output. If the filename begins
- with `>>', the file is opened for appending. (You can put a `+'
- in front of the `>' or `<' to indicate that you want both read and
- write access to the file.) If the filename begins with `|', the
- filename is interpreted as a command to which output is to be
- piped, and if the filename ends with a `|', the filename is
- interpreted as command which pipes input to us. (You may not have
- a command that pipes both in and out.) Opening `-' opens `STDIN'
- and opening `>-' opens `STDOUT'. `open' returns non-zero upon
- success, the undefined value otherwise. If the open involved a
- pipe, the return value happens to be the pid of the subprocess.
- Examples:
-
- $article = 100;
- open article || die "Can't find article $article: $!\n";
- while (<article>) {...
-
- open(LOG, '>>/usr/spool/news/twitlog');
- # (log is reserved)
-
- open(article, "caesar <$article |");
- # decrypt article
-
- open(extract, "|sort >/tmp/Tmp$$");
- # $$ is our process#
-
- # process argument list of files along with any includes
-
- foreach $file (@ARGV) {
- do process($file, 'fh00'); # no pun intended
- }
-
- sub process {
- local($filename, $input) = @_;
- $input++; # this is a string increment
- unless (open($input, $filename)) {
- print STDERR "Can't open $filename: $!\n";
- return;
- }
- while (<$input>) { # note the use of indirection
- if (/^#include "(.*)"/) {
- do process($1, $input);
- next;
- }
- ... # whatever
- }
- }
-
- You may also, in the Bourne shell tradition, specify an EXPR
- beginning with `>&', in which case the rest of the string is
- interpreted as the name of a filehandle (or file descriptor, if
- numeric) which is to be duped and opened. You may use `&' after
- `>', `>>', `<', `+>', `+>>' and `+<'. The mode you specify should
- match the mode of the original filehandle. Here is a script that
- saves, redirects, and restores `STDOUT' and `STDERR':
-
- #!/usr/bin/perl
- open(SAVEOUT, ">&STDOUT");
- open(SAVEERR, ">&STDERR");
-
- open(STDOUT, ">foo.out") || die "Can't redirect stdout";
- open(STDERR, ">&STDOUT") || die "Can't dup stdout";
-
- select(STDERR); $| = 1; # make unbuffered
- select(STDOUT); $| = 1; # make unbuffered
-
- print STDOUT "stdout 1\n"; # this works for
- print STDERR "stderr 1\n"; # subprocesses too
-
- close(STDOUT);
- close(STDERR);
-
- open(STDOUT, ">&SAVEOUT");
- open(STDERR, ">&SAVEERR");
-
- print STDOUT "stdout 2\n";
- print STDERR "stderr 2\n";
-
- If you open a pipe on the command `-', i.e. either `|-' or `-|',
- then there is an implicit fork done, and the return value of open
- is the pid of the child within the parent process, and 0 within the
- child process. (Use `defined($pid)' to determine if the `open'
- was successful.) The filehandle behaves normally for the parent,
- but i/o to that filehandle is piped from/to the `STDOUT'/`STDIN'
- of the child process. In the child process the filehandle isn't
- opened--i/o happens from/to the new `STDOUT' or `STDIN'.
- Typically this is used like the normal piped `open' when you want
- to exercise more control over just how the pipe command gets
- executed, such as when you are running setuid, and don't want to
- have to scan shell commands for metacharacters. The following
- pairs are equivalent:
-
- open(FOO, "|tr '[a-z]' '[A-Z]'");
- open(FOO, "|-") || exec 'tr', '[a-z]', '[A-Z]';
-
- open(FOO, "cat -n '$file'|");
- open(FOO, "-|") || exec 'cat', '-n', $file;
-
- Explicitly closing any piped filehandle causes the parent process
- to wait for the child to finish, and returns the status value in
- `$?'. Note: on any operation which may do a fork, unflushed
- buffers remain unflushed in both processes, which means you may
- need to set `$|' to avoid duplicate output.
-
- The filename that is passed to open will have leading and trailing
- whitespace deleted. In order to open a file with arbitrary weird
- characters in it, it's necessary to protect any leading and
- trailing whitespace thusly:
-
- $file =~ s#^(\s)#./$1#;
- open(FOO, "< $file\0");
-
- pipe(READHANDLE,WRITEHANDLE)
- Opens a pair of connected pipes like the corresponding system call.
- Note that if you set up a loop of piped processes, deadlock can
- occur unless you are very careful. In addition, note that perl's
- pipes use stdio buffering, so you may need to set `$|' to flush
- your WRITEHANDLE after each command, depending on the application.
- [Requires version 3.0 patchlevel 9.]
-
- print(FILEHANDLE LIST)
- print(LIST)
- print FILEHANDLE LIST
- print LIST
- print
- Prints a string or a comma-separated list of strings. Returns
- non-zero if successful. FILEHANDLE may be a scalar variable name,
- in which case the variable contains the name of the filehandle,
- thus introducing one level of indirection. (NOTE: If FILEHANDLE
- is a variable and the next token is a term, it may be
- misinterpreted as an operator unless you interpose a `+' or put
- parens around the arguments.) If FILEHANDLE is omitted, prints by
- default to standard output (or to the last selected output
- channel--see `select()'). If LIST is also omitted, prints `$_' to
- `STDOUT'. To set the default output channel to something other
- than `STDOUT' use the select operation. Note that, because
- `print' takes a LIST, anything in the LIST is evaluated in an
- array context, and any subroutine that you call will have one or
- more of its expressions evaluated in an array context. Also be
- careful not to follow the `print' keyword with a left parenthesis
- unless you want the corresponding right parenthesis to terminate
- the arguments to the `print'--interpose a `+' or put parens around
- all the arguments.
-
- printf(FILEHANDLE LIST)
- printf(LIST)
- printf FILEHANDLE LIST
- printf LIST
- printf
- Equivalent to a `print FILEHANDLE sprintf(LIST)'.
-
- read(FILEHANDLE,SCALAR,LENGTH,OFFSET)
- read(FILEHANDLE,SCALAR,LENGTH)
- Attempts to read LENGTH bytes of data into variable SCALAR from
- the specified FILEHANDLE. Returns the number of bytes actually
- read, or `undef' if there was an error. SCALAR will be grown or
- shrunk to the length actually read. An OFFSET may be specified to
- place the read data at some other place than the beginning of the
- string. This call is actually implemented in terms of stdio's
- `fread' call. To get a true `read' system call, see `sysread'.
-
- select(RBITS,WBITS,EBITS,TIMEOUT)
- This calls the select system call with the bitmasks specified,
- which can be constructed using `fileno()' and `vec()', along these
- lines:
-
- $rin = $win = $ein = '';
- vec($rin,fileno(STDIN),1) = 1;
- vec($win,fileno(STDOUT),1) = 1;
- $ein = $rin | $win;
-
- If you want to select on many filehandles you might wish to write a
- subroutine:
-
- sub fhbits {
- local(@fhlist) = split(' ',$_[0]);
- local($bits);
- for (@fhlist) {
- vec($bits,fileno($_),1) = 1;
- }
- $bits;
- }
- $rin = &fhbits('STDIN TTY SOCK');
-
- The usual idiom is:
-
- ($nfound,$timeleft) =
- select($rout=$rin, $wout=$win, $eout=$ein, $timeout);
-
- or to block until something becomes ready:
-
- $nfound = select($rout=$rin, $wout=$win,
- $eout=$ein, undef);
-
- Any of the bitmasks can also be `undef'. The timeout, if
- specified, is in seconds, which may be fractional. NOTE: not all
- implementations are capable of returning the `$timeleft'. If not,
- they always return `$timeleft' equal to the supplied `$timeout'.
-
- seek(FILEHANDLE,POSITION,WHENCE)
- Randomly positions the file pointer for FILEHANDLE, just like the
- `fseek()' call of stdio. FILEHANDLE may be an expression whose
- value gives the name of the filehandle. Returns 1 upon success, 0
- otherwise.
-
- select(FILEHANDLE)
- select
- Returns the currently selected filehandle. Sets the current
- default filehandle for output, if FILEHANDLE is supplied. This
- has two effects: first, a `write' or a `print' without a filehandle
- will default to this FILEHANDLE. Second, references to variables
- related to output will refer to this output channel. For example,
- if you have to set the top of form format for more than one output
- channel, you might do the following:
-
- select(REPORT1);
- $^ = 'report1_top';
- select(REPORT2);
- $^ = 'report2_top';
-
- FILEHANDLE may be an expression whose value gives the name of the
- actual filehandle. Thus:
-
- $oldfh = select(STDERR); $| = 1; select($oldfh);
-
- tell(FILEHANDLE)
- tell FILEHANDLE
- tell
- Returns the current file position for FILEHANDLE. FILEHANDLE may
- be an expression whose value gives the name of the actual
- filehandle. If FILEHANDLE is omitted, assumes the file last read.
-
- write(FILEHANDLE)
- write(EXPR)
- write
- Writes a formatted record (possibly multi-line) to the specified
- file, using the format associated with that file. By default the
- format for a file is the one having the same name is the
- filehandle, but the format for the current output channel (see
- `select') may be set explicitly by assigning the name of the
- format to the `$~' variable.
-
- Top of form processing is handled automatically: if there is
- insufficient room on the current page for the formatted record,
- the page is advanced by writing a form feed, a special top-of-page
- format is used to format the new page header, and then the record
- is written. By default the top-of-page format is the name of the
- filehandle with `_TOP' appended, but it may be dynamically set to
- the format of your choice by assigning the name to the `$^'
- variable while the filehandle is `select'ed. The number of lines
- remaining on the current page is in variable `$-', which can be
- set to 0 to force a new page.
-
- If FILEHANDLE is unspecified, output goes to the current default
- output channel, which starts out as `STDOUT' but may be changed by
- the `select' operator. If the FILEHANDLE is an EXPR, then the
- expression is evaluated and the resulting string is used to look
- up the name of the FILEHANDLE at run time. *Note Formats::, for
- more info.
-
- Note that `write' is NOT the opposite of `read'.
-
-