Add documentation for default UNIVERSAL methods
[p5sagit/p5-mst-13.2.git] / pod / perlfunc.pod
index 6104eb5..a6af80a 100644 (file)
@@ -119,7 +119,7 @@ pack, read, syscall, sysread, syswrite, unpack, vec
 
 =item Functions for filehandles, files, or directories
 
--X, chdir, chmod, chown, chroot, fcntl, glob, ioctl, link,
+I<-X>, chdir, chmod, chown, chroot, fcntl, glob, ioctl, link,
 lstat, mkdir, open, opendir, readlink, rename, rmdir,
 stat, symlink, umask, unlink, utime
 
@@ -149,7 +149,7 @@ do, import, no, package, require, use
 
 =item Keywords related to classes and object-orientedness
 
-bless, dbmclose, dbmopen, package, ref, tie, untie, use
+bless, dbmclose, dbmopen, package, ref, tie, tied, untie, use
 
 =item Low-level socket functions
 
@@ -180,6 +180,20 @@ setnetent, setprotoent, setservent
 
 gmtime, localtime, time, times
 
+=item Functions new in perl5
+
+abs, bless, chomp, chr, exists, formline, glob, import, lc,
+lcfirst, map, my, no, prototype, qx, qw, readline, readpipe,
+ref, sub*, sysopen, tie, tied, uc, ucfirst, untie, use
+
+* - C<sub> was a keyword in perl4, but in perl5 it is an
+operator which can be used in expressions.
+
+=item Functions obsoleted in perl5
+
+dbmclose, dbmopen
+
+
 =back
 
 =head2 Alphabetical Listing of Perl Functions
@@ -628,6 +642,21 @@ Examples:
 
 See also undef().
 
+Note: many folks tend to overuse defined(), and then are surprised to
+discover that the number 0 and the null string are, in fact, defined
+concepts.  For example, if you say
+
+    "ab" =~ /a(.*)b/;
+
+the pattern match succeeds, and $1 is defined, despite the fact that it
+matched "nothing".  But it didn't really match nothing--rather, it
+matched something that happened to be 0 characters long.  This is all
+very above-board and honest.  When a function returns an undefined value,
+it's an admission that it couldn't give you an honest answer.  So
+you should only use defined() when you're questioning the integrity
+of what you're trying to do.  At other times, a simple comparison to
+0 or "" is what you want.
+
 =item delete EXPR
 
 Deletes the specified value from its hash array.  Returns the deleted
@@ -747,11 +776,14 @@ Example:
 
 =item 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.
+When called in a list context, returns a 2-element array consisting
+of the key and value for the next element of an associative array,
+so that you can iterate over it.  When called in a scalar context,
+returns the key only for the next element in the associative array.
 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
+entirely read, a null array is returned in list context (which when
+assigned produces a FALSE (0) value), and C<undef> is returned in a
+scalar context.  The next call to each() after that will start
 iterating again.  The iterator can be reset only by reading all the
 elements from the array.  You should not add elements to an array while
 you're iterating over it.  There is a single iterator for each
@@ -782,9 +814,9 @@ as terminals may lose the end-of-file condition if you do.
 An C<eof> without an argument uses the last file read as argument.
 Empty parentheses () may be used to indicate
 the pseudofile formed of the files listed on the command line, i.e.
-C<eof()> is reasonable to use inside a while (<>) loop to detect the end
+C<eof()> is reasonable to use inside a while (E<lt>E<gt>) loop to detect the end
 of only the last file.  Use C<eof(ARGV)> or eof without the parentheses to
-test I<EACH> file in a while (<>) loop.  Examples:
+test I<EACH> file in a while (E<lt>E<gt>) loop.  Examples:
 
     # reset line numbering on each input file
     while (<>) {
@@ -803,7 +835,7 @@ test I<EACH> file in a while (<>) loop.  Examples:
     }
 
 Practical hint: you almost never need to use C<eof> in Perl, because the
-input operators return undef when they run out of data.  Testing C<eof>
+input operators return undef when they run out of data.  
 
 =item eval EXPR
 
@@ -875,7 +907,7 @@ there is only one scalar argument, the argument is checked for shell
 metacharacters.  If there are any, the entire argument is passed to
 C</bin/sh -c> for parsing.  If there are none, the argument is split
 into words and passed directly to execvp(), which is more efficient.
-Note: exec() (and system(0) do not flush your output buffer, so you may
+Note: exec() and system() do not flush your output buffer, so you may
 need to set C<$|> to avoid lost output.  Examples:
 
     exec '/bin/echo', 'Your arguments are: ', @ARGV;
@@ -1094,7 +1126,7 @@ getpwuid().
 
     $login = getlogin || (getpwuid($<))[0] || "Kilroy";
 
-Do not consider getlogin() for authorentication: it is not as
+Do not consider getlogin() for authentication: it is not as
 secure as getpwuid().
 
 =item getpeername SOCKET
@@ -1426,7 +1458,7 @@ Unlike in the shell, in Perl if the I<SIGNAL> is negative, it kills
 process groups instead of processes.  (On System V, a negative I<PROCESS>
 number will also kill process groups, but that's not portable.)  That
 means you usually want to use positive not negative signals.  You may also
-use a signal name in quotes.  See the L<perlipc/"Signals"> man page for details.
+use a signal name in quotes.  See L<perlipc/"Signals"> for details.
 
 =item last LABEL
 
@@ -1497,8 +1529,8 @@ In a scalar context, prints out the ctime(3) value:
 
     $now_string = localtime;  # e.g. "Thu Oct 13 04:54:34 1994"
 
-See also L<perlmod/timelocal> and the strftime(3) function available
-via the POSIX modulie.
+Also see the F<timelocal.pl> library, and the strftime(3) function available
+via the POSIX module.
 
 =item log EXPR
 
@@ -1561,7 +1593,7 @@ or the undefined value if there is an error.
 
 Calls the System V IPC function msgsnd to send the message MSG to the
 message queue ID.  MSG must begin with the long integer message type,
-which may be created with C<pack("L", $type)>.  Returns TRUE if
+which may be created with C<pack("l", $type)>.  Returns TRUE if
 successful, or FALSE if there is an error.
 
 =item msgrcv ID,VAR,SIZE,TYPE,FLAGS
@@ -1631,7 +1663,7 @@ 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 See L<perlipc/"Using open() for IPC">
 for more examples of this.  as command which pipes input to us.  (You may
-not have a raw open() to a command that pipes both in I<and> out, but see See L<open2>,
+not have a raw open() to a command that pipes both in I<and> out, but see L<open2>,
 L<open3>, and L<perlipc/"Bidirectional Communication"> for alternatives.)
 
 Opening '-' opens STDIN and opening '>-' opens STDOUT.  Open returns
@@ -1647,7 +1679,6 @@ and those that don't is their text file formats.  Systems like Unix and
 Plan9 that delimit lines with a single character, and that encode that
 character in C as '\n', do not need C<binmode>.  The rest need it.
 
-
 Examples:
 
     $ARTICLE = 100;
@@ -1751,6 +1782,24 @@ 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.
 
+Using the FileHandle constructor from the FileHandle package,
+you can generate anonymous filehandles which have the scope of whatever
+variables hold references to them, and automatically close whenever
+and however you leave that scope:
+
+    use FileHandle;
+    ...
+    sub read_myfile_munged {
+       my $ALL = shift;
+       my $handle = new FileHandle;
+       open($handle, "myfile") or die "myfile: $!";
+       $first = <$handle>
+           or return ();     # Automatically closed here.
+       mung $first or die "mung failed";       # Or here.
+       return $first, <$handle> if $ALL;       # Or here.
+       $first;                                 # Or here.
+    }
+
 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
@@ -1759,19 +1808,17 @@ whitespace thusly:
     $file =~ s#^(\s)#./$1#;
     open(FOO, "< $file\0");
 
-If you want a "real" C open() (see L<open(2)) on your system, then
-you should probably use the POSIX::open() function as found in the L<POSIX> 
-documents.  For example:
+If you want a "real" C open() (see L<open(2)> on your system), then
+you should use the sysopen() function.  This is another way to
+protect your filenames from interpretation.  For example:
 
     use FileHandle;
-    use POSIX qw(:fcntl_h);
-    $fd = POSIX::open($path, O_RDWR|O_CREAT|O_EXCL, 0700);
-    die "POSIX::open $path: $!" unless defined $fd;
-    $fh = FileHandle->new_from_fd($fd, $amode) || die "fdopen: $!";
-    $fh->autoflush(1);
-    $fh->print("stuff $$\n");
-    seek($fh, 0, SEEK_SET);
-    print "File contains: ", <$fh>;
+    sysopen(HANDLE, $path, O_RDWR|O_CREAT|O_EXCL, 0700)
+       or die "sysopen $path: $!";
+    HANDLE->autoflush(1);
+    HANDLE->print("stuff $$\n");
+    seek(HANDLE, 0, 0);
+    print "File contains: ", <HANDLE>;
 
 See L</seek()> for some details about mixing reading and writing.
 
@@ -1938,7 +1985,7 @@ 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
+output channel--see L</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 a list context, and any
@@ -1949,7 +1996,7 @@ parenthesis to terminate the arguments to the print--interpose a + or
 put parens around all the arguments.
 
 Note that if you're storing FILEHANDLES in an array or other expression,
-you will have to use a block returning its value instead
+you will have to use a block returning its value instead:
 
     print { $files[$i] } "stuff\n";
     print { $OK ? STDOUT : STDERR } "stuff\n";
@@ -1961,6 +2008,12 @@ you will have to use a block returning its value instead
 Equivalent to a "print FILEHANDLE sprintf(LIST)".  The first argument
 of the list will be interpreted as the printf format.
 
+=item prototype FUNCTION
+
+Returns the prototype of a function as a string (or C<undef> if the
+function has no prototype).  FUNCTION is a reference to the the
+function whose prototype you want to retrieve.
+
 =item push ARRAY,LIST
 
 Treats ARRAY as a stack, and pushes the values of LIST
@@ -2146,11 +2199,12 @@ end such a file with "1;" unless you're sure it'll return TRUE
 otherwise.  But it's better just to put the "C<1;>", in case you add more
 statements.
 
-If EXPR is a bare word, the require assumes a "F<.pm>" extension for you,
+If EXPR is a bare word, the require assumes a "F<.pm>" extension and
+replaces "F<::>" with "F</>" in the filename for you,
 to make it easy to load standard modules.  This form of loading of 
 modules does not risk altering your namespace.
 
-For a yet-more-powerful import facility, see the L</use()> and 
+For a yet-more-powerful import facility, see L</use> and 
 L<perlmod>.
 
 =item reset EXPR
@@ -2173,7 +2227,7 @@ resets variables or searches in the current package.  Always returns
 Resetting "A-Z" is not recommended since you'll wipe out your
 ARGV and ENV arrays.  Only resets package variables--lexical variables
 are unaffected, but they clean themselves up on scope exit anyway,
-so anymore you probably want to use them instead.  See L</my>.
+so you'll probably want to use them instead.  See L</my>.
 
 =item return LIST
 
@@ -2250,7 +2304,7 @@ EOF on your read, and then sleep for a while, you might have to stick in a
 seek() to reset things.  First the simple trick listed above to clear the
 filepointer.  The seek() doesn't change the current position, but it
 I<does> clear the end-of-file condition on the handle, so that the next
-C<E<lt>FILE<E<gt>> makes Perl try again to read something.  Hopefully.
+C<E<lt>FILEE<gt>> makes Perl try again to read something.  Hopefully.
 
 If that doesn't work (some stdios are particularly cantankerous), then
 you may need something more like this:
@@ -2326,16 +2380,19 @@ The usual idiom is:
     ($nfound,$timeleft) =
       select($rout=$rin, $wout=$win, $eout=$ein, $timeout);
 
-or to block until something becomes ready:
+or to block until something becomes ready just do this 
 
     $nfound = select($rout=$rin, $wout=$win, $eout=$ein, undef);
 
+Most systems do not both to return anything useful in $timeleft, so
+calling select() in a scalar context just returns $nfound.
+
 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.
 
-You can effect a 250-microsecond sleep this way:
+You can effect a 250-millisecond sleep this way:
 
     select(undef, undef, undef, 0.25);
 
@@ -2525,6 +2582,10 @@ Examples:
     }
     @sortedclass = sort byage @class;
 
+    # this sorts the %age associative arrays by value 
+    # instead of key using an inline function
+    @eldest = sort { $age{$b} <=> $age{$a} } keys %age;
+
     sub backwards { $b cmp $a; }
     @harry = ('dog','cat','x','Cain','Abel');
     @george = ('gone','chased','yz','Punished','Axed');
@@ -2660,7 +2721,7 @@ 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");
+    split(/([,-])/, "1-10,20", 3);
 
 produces the list value
 
@@ -2713,8 +2774,8 @@ root of $_.
 =item srand EXPR
 
 Sets the random number seed for the C<rand> operator.  If EXPR is omitted,
-does C<srand(time)>.  Many folks use an explicit C<srand(time ^ $$)>
-instead.  Of course, you'd need something much more random than that for
+uses a semirandom value based on the current time and process ID, among
+other things.  Of course, you'd need something much more random than that for
 cryptographic purposes, since it's easy to guess the current time.
 Checksumming the compressed output of rapidly changing operating system
 status programs is the usual method.  Examples are posted regularly to
@@ -2732,6 +2793,25 @@ the stat fails.  Typically used as follows:
        $atime,$mtime,$ctime,$blksize,$blocks)
            = stat($filename);
 
+Not all fields are supported on all filesystem types.  Here are the 
+meaning of the fields:
+
+  dev      device number of filesystem 
+  ino      inode number 
+  mode     file mode  (type and permissions)
+  nlink            number of (hard) links to the file 
+  uid      numeric user ID of file's owner 
+  gid      numer group ID of file's owner 
+  rdev     the device identifier (special files only)
+  size     total size of file, in bytes 
+  atime            last access time since the epoch
+  mtime            last modify time since the epoch
+  ctime            inode change time (NOT creation type!) since the epoch
+  blksize   preferred blocksize for file system I/O
+  blocks    actual number of blocks allocated
+
+(The epoch was at 00:00 January 1, 1970 GMT.)
+
 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:
@@ -2858,6 +2938,27 @@ like numbers.
 Note that Perl only supports passing of up to 14 arguments to your system call,
 which in practice should usually suffice.
 
+=item sysopen FILEHANDLE,FILENAME,MODE
+
+=item sysopen FILEHANDLE,FILENAME,MODE,PERMS
+
+Opens the file whose filename is given by FILENAME, and associates it
+with FILEHANDLE.  If FILEHANDLE is an expression, its value is used as
+the name of the real filehandle wanted.  This function calls the
+underlying operating system's C<open> function with the parameters
+FILENAME, MODE, PERMS.
+
+The possible values and flag bits of the MODE parameter are
+system-dependent; they are available via the standard module C<Fcntl>.
+However, for historical reasons, some values are universal: zero means
+read-only, one means write-only, and two means read/write.
+
+If the file named by FILENAME does not exist and the C<open> call
+creates it (typically because MODE includes the O_CREAT flag), then
+the value of PERMS specifies the permissions of the newly created
+file.  If PERMS is omitted, the default value is 0666, which allows
+read and write for all.  This default is reasonable: see C<umask>.
+
 =item sysread FILEHANDLE,SCALAR,LENGTH,OFFSET
 
 =item sysread FILEHANDLE,SCALAR,LENGTH
@@ -2889,7 +2990,7 @@ Attempts to write LENGTH bytes of data from variable SCALAR to the
 specified FILEHANDLE, using the system call write(2).  It bypasses
 stdio, so mixing this with prints may cause confusion.  Returns the
 number of bytes actually written, or undef if there was an error.  An
-OFFSET may be specified to place the read data at some other place than
+OFFSET may be specified to get the write data from some other place than
 the beginning of the string.
 
 =item tell FILEHANDLE
@@ -2925,7 +3026,7 @@ use the each() function to iterate over such.  Example:
 
     # print out history file offsets
     use NDBM_File;
-    tie(%HIST, NDBM_File, '/usr/lib/news/history', 1, 0);
+    tie(%HIST, 'NDBM_File', '/usr/lib/news/history', 1, 0);
     while (($key,$val) = each %HIST) {
        print $key, ' = ', unpack('L',$val), "\n";
     }
@@ -2962,10 +3063,19 @@ Unlike dbmopen(), the tie() function will not use or require a module
 for you--you need to do that explicitly yourself.  See L<DB_File>
 or the F<Config> module for interesting tie() implementations.
 
+=item tied VARIABLE
+
+Returns a reference to the object underlying VARIABLE (the same value
+that was originally returned by the tie() call which bound the variable
+to a package.)  Returns the undefined value if VARIABLE isn't tied to a
+package.
+
 =item time
 
-Returns the number of non-leap seconds since 00:00:00 UTC, January 1,
-1970.  Suitable for feeding to gmtime() and localtime().
+Returns the number of non-leap seconds since whatever time the system
+considers to be the epoch (that's 00:00:00, January 1, 1904 for MacOS,
+and 00:00:00 UTC, January 1, 1970 for most other systems).
+Suitable for feeding to gmtime() and localtime().
 
 =item times
 
@@ -3089,12 +3199,26 @@ reverse.
 
 =item use Module
 
+=item use Module VERSION LIST
+
+=item use VERSION
+
 Imports some semantics into the current package from the named module,
 generally by aliasing certain subroutine or variable names into your
 package.  It is exactly equivalent to
 
     BEGIN { require Module; import Module LIST; }
 
+except that Module I<must> be a bare word.
+
+If the first argument to C<use> is a number, it is treated as a version
+number instead of a module name.  If the version of the Perl interpreter
+is less than VERSION, then an error message is printed and Perl exits
+immediately.  This is often useful if you need to check the current
+Perl version before C<use>ing library modules which have changed in
+incompatible ways from older versions of Perl.  (We try not to do
+this more than we have to.)
+
 The BEGIN forces the require and import to happen at compile time.  The
 require makes sure the module is loaded into memory if it hasn't been
 yet.  The import is not a builtin--it's just an ordinary static method
@@ -3112,6 +3236,10 @@ That is exactly equivalent to
 
     BEGIN { require Module; }
 
+If the VERSION argument is present between Module and LIST, then the
+C<use> will fail if the C<$VERSION> variable in package Module is
+less than VERSION.
+
 Because this is a wide-open interface, pragmas (compiler directives)
 are also implemented this way.  Currently implemented pragmas are:
 
@@ -3126,7 +3254,7 @@ ordinary modules, which import symbols into the current package (which are
 effective through the end of the file).
 
 There's a corresponding "no" command that unimports meanings imported
-by use.
+by use, i.e. it calls C<unimport Module LIST> instead of C<import>.
 
     no integer;
     no strict 'refs';
@@ -3151,13 +3279,18 @@ Returns a normal array consisting of all the values of the named
 associative array.  (In a scalar context, returns the number of
 values.)  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().
+on the same array.  See also keys(), each(), and sort().
 
 =item vec EXPR,OFFSET,BITS
 
-Treats a string as a vector of unsigned integers, and returns the value
-of the bitfield specified.  May also be assigned to.  BITS must be a
-power of two from 1 to 32.
+Treats the string in EXPR as a vector of unsigned integers, and
+returns the value of the bitfield specified by OFFSET.  BITS specifies
+the number of bits that are reserved for each entry in the bit
+vector. This must be a power of two from 1 to 32. vec() may also be
+assigned to, in which case parens are needed to give the expression
+the correct precedence as in
+
+    vec($image, $max_x * $x + $y, 8) = 3;
 
 Vectors created with vec() can also be manipulated with the logical
 operators |, & and ^, which will assume a bit vector operation is
@@ -3238,6 +3371,6 @@ Note that write is I<NOT> the opposite of read.  Unfortunately.
 
 =item y///
 
-The translation operator.  See L<perlop/tr///>.
+The translation operator.  See L<perlop>.
 
 =back