This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
patch for LWP 5.05 to make it play with both 5.003 and 5.003_20 + overload patch
[perl5.git] / pod / perlfunc.pod
index fe3da14..34d9281 100644 (file)
@@ -56,9 +56,7 @@ Remember the following rule:
 
 =over 8
 
-=item  
-
-I<THERE IS NO GENERAL RULE FOR CONVERTING A LIST INTO A SCALAR!>
+=item  I<THERE IS NO GENERAL RULE FOR CONVERTING A LIST INTO A SCALAR!>
 
 =back
 
@@ -283,8 +281,8 @@ file, or a file at EOF when testing a filehandle.  Because you have to
 read a file to do the C<-T> test, on most occasions you want to use a C<-f>
 against the file first, as in C<next unless -f $file && -T $file>.
 
-If any of the file tests (or either the stat() or lstat() operators) are given the
-special filehandle consisting of a solitary underline, then the stat
+If any of the file tests (or either the stat() or lstat() operators) 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 C<-t>, and you need to remember
 that lstat() and C<-l> will leave values in the stat structure for the
@@ -340,7 +338,7 @@ fail with $! set to EINTR because Perl sets up signal handlers to
 restart system calls on some systems.  Using eval/die always works.
 
     eval {
-       local $SIG{ALRM} = sub { die "alarm\n" };       # NB \n required
+       local $SIG{ALRM} = sub { die "alarm\n" };       # NB \n required
        alarm $timeout;
        $nread = sysread SOCKET, $buffer, $size;
        alarm 0;
@@ -357,6 +355,11 @@ restart system calls on some systems.  Using eval/die always works.
 
 Returns the arctangent of Y/X in the range -PI to PI.
 
+For the tangent operation, you may use the POSIX::tan()
+function, or use the familiar relation:
+
+    sub tan { sin($_[0]) / cos($_[0])  }
+
 =item bind SOCKET,NAME
 
 Binds a network address to a socket, just as the bind system call
@@ -382,7 +385,7 @@ is taken as the name of the filehandle.
 
 =item bless REF
 
-This function tells the referenced object (passed as REF) that it is now
+This function tells the thingy referenced by REF that it is now
 an object in the CLASSNAME package--or the current package if no CLASSNAME
 is specified, which is often the case.  It returns the reference for
 convenience, because a bless() is often the last thing in a constructor.
@@ -395,8 +398,9 @@ blessing (and blessings) of objects.
 =item caller
 
 Returns the context of the current subroutine call.  In a scalar context,
-returns TRUE if there is a caller, that is, if we're in a subroutine or
-eval() or require(), and FALSE otherwise.  In a list context, returns
+returns the caller's package name if there is a caller, that is, if
+we're in a subroutine or eval() or require(), and the undefined value
+otherwise.  In a list context, returns
 
     ($package, $filename, $line) = caller;
 
@@ -404,8 +408,17 @@ With EXPR, it returns some extra information that the debugger uses to
 print a stack trace.  The value of EXPR indicates how many call frames
 to go back before the current one.
 
-    ($package, $filename, $line,
-     $subroutine, $hasargs, $wantargs) = caller($i);
+    ($package, $filename, $line, $subroutine, 
+     $hasargs, $wantarray, $evaltext, $is_require) = caller($i);
+
+Here $subroutine may be C<"(eval)"> if the frame is not a subroutine
+call, but C<L<eval>>. In such a case additional elements $evaltext and
+$is_require are set: $is_require is true if the frame is created by
+C<L<require>> or C<L<use>> statement, $evaltext contains the text of
+C<L<eval EXPR>> statement. In particular, for C<L<eval BLOCK>>
+statement $filename is C<"(eval)">, but $evaltext is undefined. (Note
+also that C<L<use>> statement creates a C<L<require>> frame inside
+an C<L<eval EXPR>>) frame.
 
 Furthermore, when called from within the DB package, caller returns more
 detailed information: it sets the list variable @DB::args to be the
@@ -434,12 +447,12 @@ number.  Returns the number of files successfully changed.
 
 This is a slightly safer version of chop (see below).  It removes any
 line ending that corresponds to the current value of C<$/> (also known as
-$INPUT_RECORD_SEPARATOR in the C<English> module).  It returns the number
-of characters removed.  It's often used to remove the newline from the
-end of an input record when you're worried that the final record may be
-missing its newline.  When in paragraph mode (C<$/ = "">), it removes all
-trailing newlines from the string.  If VARIABLE is omitted, it chomps
-$_.  Example:
+$INPUT_RECORD_SEPARATOR in the C<English> module).  It returns the total
+number of characters removed from all its arguments.  It's often used to
+remove the newline from the end of an input record when you're worried
+that the final record may be missing its newline.  When in paragraph mode
+(C<$/ = "">), it removes all trailing newlines from the string.  If
+VARIABLE is omitted, it chomps $_.  Example:
 
     while (<>) {
        chomp;  # avoid \n on last field
@@ -527,7 +540,7 @@ If NUMBER is omitted, uses $_.
 This function works as the system call by the same name: it makes the
 named directory the new root directory for all further pathnames that
 begin with a "/" by your process and all of its children.  (It doesn't
-change your current working directory is unaffected.)  For security
+change your current working directory, which is unaffected.)  For security
 reasons, this call is restricted to the superuser.  If FILENAME is
 omitted, does chroot to $_.
 
@@ -577,6 +590,11 @@ statement).
 Returns the cosine of EXPR (expressed in radians).  If EXPR is omitted
 takes cosine of $_.
 
+For the inverse cosine operation, you may use the POSIX::acos()
+function, or use this relation:
+
+    sub acos { atan2( sqrt(1 - $_[0] * $_[0]), $_[0] ) }
+
 =item crypt PLAINTEXT,SALT
 
 Encrypts a string exactly like the crypt(3) function in the C library
@@ -691,6 +709,24 @@ you should use defined() only 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.
 
+Another surprise is that using defined() on an entire array or 
+hash reports whether memory for that aggregate has ever been
+allocated.  So an array you set to the empty list appears undefined
+initially, and one that once was full and that you then set to 
+the empty list still appears defined.  You should instead use a 
+simple test for size:
+
+    if (@an_array) { print "has array elements\n" }
+    if (%a_hash)   { print "has hash members\n"   }
+
+Using undef() on these, however, does clear their memory and then report
+them as not defined anymore, but you shoudln't do that unless you don't
+plan to use them again, because it saves time when you load them up
+again to have memory already ready to be filled.
+
+This counter-intuitive behaviour of defined() on aggregates may be
+changed, fixed, or broken in a future release of Perl.
+
 =item delete EXPR
 
 Deletes the specified key(s) and their associated values from a hash
@@ -721,10 +757,10 @@ hash element lookup or hash slice:
 
 Outside of an eval(), prints the value of LIST to C<STDERR> and exits with
 the current value of C<$!> (errno).  If C<$!> is 0, exits with the value of
-C<($? E<gt>E<gt> 8)> (back-tick `command` status).  If C<($? E<gt>E<gt> 8)> is 0,
-exits with 255.  Inside an eval(), the error message is stuffed into C<$@>,
-and the eval() is terminated with the undefined value; this makes die()
-the way to raise an exception.
+C<($? E<gt>E<gt> 8)> (back-tick `command` status).  If C<($? E<gt>E<gt> 8)>
+is 0, exits with 255.  Inside an eval(), the error message is stuffed into
+C<$@>, and the eval() is terminated with the undefined value; this makes
+die() the way to raise an exception.
 
 Equivalent examples:
 
@@ -1000,6 +1036,10 @@ are called before exit.)  Example:
 
 See also die().  If EXPR is omitted, exits with 0 status.
 
+You shouldn't use exit() to abort a subroutine if there's any chance that
+someone might want to trap whatever error happened.  Use die() instead,
+which can be trapped by an eval().
+
 =item exp EXPR
 
 =item exp 
@@ -1029,14 +1069,35 @@ value is taken as the name of the filehandle.
 
 =item flock FILEHANDLE,OPERATION
 
-Calls flock(2) on FILEHANDLE.  See L<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 either flock(2) or
-fcntl(2). The fcntl(2) system call will be automatically used if flock(2)
-is missing from your system.  This makes flock() the portable file locking
-strategy, although it will lock only entire files, not records.  Note also
-that some versions of flock() cannot lock things over the network; you
-would need to use the more system-specific fcntl() for that.
+Calls flock(2), or an emulation of it, on FILEHANDLE.  Returns TRUE for
+success, FALSE on failure.  Will produce a fatal error if used on a
+machine that doesn't implement flock(2), fcntl(2) locking, or lockf(3).
+flock() is Perl's portable file locking interface, although it will lock
+only entire files, not records.
+
+OPERATION is one of LOCK_SH, LOCK_EX, or LOCK_UN, possibly combined with
+LOCK_NB.  These constants are traditionally valued 1, 2, 8 and 4, but
+you can use the symbolic names if you pull them in with an explicit
+request to the Fcntl module.  The names can be requested as a group with
+the :flock tag (or they can be requested individually, of course).
+LOCK_SH requests a shared lock, LOCK_EX requests an exclusive lock, and
+LOCK_UN releases a previously requested lock.  If LOCK_NB is added to
+LOCK_SH or LOCK_EX then flock() will return immediately rather than
+blocking waiting for the lock (check the return status to see if you got
+it).
+
+Note that the emulation built with lockf(3) doesn't provide shared
+locks, and it requires that FILEHANDLE be open with write intent.  These
+are the semantics that lockf(3) implements.  Most (all?) systems
+implement lockf(3) in terms of fcntl(2) locking, though, so the
+differing semantics shouldn't bite too many people.
+
+Note also that some versions of flock() cannot lock things over the
+network; you would need to use the more system-specific fcntl() for
+that.  If you like you can force Perl to ignore your system's flock(2)
+function, and so provide its own fcntl(2)-based emulation, by passing
+the switch C<-Ud_flock> to the F<Configure> program when you configure
+perl.
 
 Here's a mailbox appender for BSD systems.
 
@@ -1067,8 +1128,8 @@ See also L<DB_File> for other flock() examples.
 Does a fork(2) system call.  Returns the child pid to the parent process
 and 0 to the child process, or C<undef> if the fork is unsuccessful.
 Note: unflushed buffers remain unflushed in both processes, which means
-you may need to set C<$|> ($AUTOFLUSH in English) or call the 
-autoflush() FileHandle method to avoid duplicate output.
+you may need to set C<$|> ($AUTOFLUSH in English) or call the autoflush()
+method of IO::Handle to avoid duplicate output.
 
 If you fork() without ever waiting on your children, you will accumulate
 zombies:
@@ -1093,6 +1154,11 @@ fork() returns omitted);
 See also L<perlipc> for more examples of forking and reaping
 moribund children.
 
+Note that if your forked child inherits system file descriptors like
+STDIN and STDOUT that are actually connected by a pipe or socket, even
+if you exit, the remote server (such as, say, httpd or rsh) won't think
+you're done.  You should reopen those to /dev/null if it's any issue.
+
 =item format
 
 Declare a picture format with use by the write() function.  For
@@ -1159,8 +1225,10 @@ single-characters, however.  For that, try something more like:
 Determination of whether to whether $BSD_STYLE should be set 
 is left as an exercise to the reader.  
 
+The POSIX::getattr() function can do this more portably on systems
+alleging POSIX compliance.
 See also the C<Term::ReadKey> module from your nearest CPAN site;
-details on CPAN can be found on L<perlmod/CPAN> 
+details on CPAN can be found on L<perlmod/CPAN> 
 
 =item getlogin
 
@@ -1544,7 +1612,7 @@ C<continue> block, if any, is not executed:
 
 Returns an lowercased version of EXPR.  This is the internal function
 implementing the \L escape in double-quoted strings.  
-Should respect any POSIX setlocale() settings.
+Respects current LC_CTYPE locale if C<use locale> in force.  See L<perllocale>.
 
 If EXPR is omitted, uses $_.
 
@@ -1554,7 +1622,7 @@ If EXPR is omitted, uses $_.
 
 Returns the value of EXPR with the first character lowercased.  This is
 the internal function implementing the \l escape in double-quoted strings.
-Should respect any POSIX setlocale() settings.
+Respects current LC_CTYPE locale if C<use locale> in force.  See L<perllocale>.
 
 If EXPR is omitted, uses $_.
 
@@ -1903,7 +1971,7 @@ 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 IO::Handle;
     sysopen(HANDLE, $path, O_RDWR|O_CREAT|O_EXCL, 0700)
        or die "sysopen $path: $!";
     HANDLE->autoflush(1);
@@ -2055,6 +2123,8 @@ for examples of such things.
 
 =item pop ARRAY
 
+=item pop 
+
 Pops and returns the last value of the array, shortening the array by
 1.  Has a similar effect to
 
@@ -2071,7 +2141,9 @@ like shift().
 
 Returns the offset of where the last C<m//g> search left off for the variable
 is in question ($_ is used when the variable is not specified). May be
-modified to change that offset.
+modified to change that offset.  Such modification will also influence
+the C<\G> zero-width assertion in regular expressions.  See L<perlre> and
+L<perlop>.
 
 =item print FILEHANDLE LIST
 
@@ -2106,8 +2178,14 @@ you will have to use a block returning its value instead:
 
 =item printf FORMAT, LIST
 
-Equivalent to a "print FILEHANDLE sprintf(FORMAT, LIST)".  The first argument
-of the list will be interpreted as the printf format.
+Equivalent to C<print FILEHANDLE sprintf(FORMAT, LIST)>.  The first argument
+of the list will be interpreted as the printf format.  If C<use locale> is
+in effect, the character used for the decimal point in formatted real numbers
+is affected by the LC_NUMERIC locale.  See L<perllocale>.
+
+Don't fall into the trap of using a printf() when a simple
+print() would do.  The print() is more efficient, and less
+error prone.
 
 =item prototype FUNCTION
 
@@ -2141,8 +2219,11 @@ Generalized quotes.  See L<perlop>.
 
 =item quotemeta 
 
-Returns the value of EXPR with with all regular expression
-metacharacters backslashed.  This is the internal function implementing
+Returns the value of EXPR with with all non-alphanumeric
+characters backslashed.  (That is, all characters not matching
+C</[A-Za-z_0-9]/> will be preceded by a backslash in the
+returned string, regardless of any locale settings.)
+This is the internal function implementing
 the \Q escape in double-quoted strings.
 
 If EXPR is omitted, uses $_.
@@ -2461,7 +2542,7 @@ actual filehandle.  Thus:
 Some programmers may prefer to think of filehandles as objects with
 methods, preferring to write the last example as:
 
-    use FileHandle;
+    use IO::Handle;
     STDERR->autoflush(1);
 
 =item select RBITS,WBITS,EBITS,TIMEOUT
@@ -2617,6 +2698,11 @@ has the same interpretation as in the system call of the same name.
 Returns the sine of EXPR (expressed in radians).  If EXPR is omitted,
 returns sine of $_.
 
+For the inverse sine operation, you may use the POSIX::sin()
+function, or use this relation:
+
+    sub asin { atan2($_[0], sqrt(1 - $_[0] * $_[0])) }
+
 =item sleep EXPR
 
 =item sleep
@@ -2674,6 +2760,9 @@ the subroutine not via @_ but as the package global variables $a and
 $b (see example below).  They are passed by reference, so don't
 modify $a and $b.  And don't try to declare them as lexicals either.
 
+When C<use locale> is in effect, C<sort LIST> sorts LIST according to the
+current collation locale.  See L<perllocale>.
+
 Examples:
 
     # sort lexically
@@ -2888,7 +2977,10 @@ Returns a string formatted by the usual printf conventions of the C
 language.  See L<sprintf(3)> or L<printf(3)> on your system for details.
 (The * character for an indirectly specified length is not
 supported, but you can get the same effect by interpolating a variable
-into the pattern.)  Some C libraries' implementations of sprintf() can
+into the pattern.)  If C<use locale> is
+in effect, the character used for the decimal point in formatted real numbers
+is affected by the LC_NUMERIC locale.  See L<perllocale>.
+Some C libraries' implementations of sprintf() can
 dump core when fed ludicrous arguments.
 
 =item sqrt EXPR
@@ -2902,12 +2994,37 @@ root of $_.
 
 Sets the random number seed for the C<rand> operator.  If EXPR is omitted,
 uses a semi-random 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, because 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
-the comp.security.unix newsgroup.
+other things.  In versions of Perl prior to 5.004 the default seed was
+just the current time().  This isn't a particularly good seed, so many
+old programs supply their own seed value (often C<time ^ $$> or C<time ^
+($$ + ($$ << 15))>), but that isn't necessary any more.
 
+You need something much more random than the default seed for
+cryptographic purposes, though.  Checksumming the compressed output of
+one or more rapidly changing operating system status programs is the
+usual method. For example:
+
+    srand (time ^ $$ ^ unpack "%L*", `ps axww | gzip`);
+
+If you're particularly concerned with this, see the Math::TrulyRandom
+module in CPAN.
+
+Do I<not> call srand() multiple times in your program unless you know
+exactly what you're doing and why you're doing it.  The point of the
+function is to "seed" the rand() function so that rand() can produce
+a different sequence each time you run your program.  Just do it once at the
+top of your program, or you I<won't> get random numbers out of rand()!
+
+Frequently called programs (like CGI scripts) that simply use 
+
+    time ^ $$
+
+for a seed can fall prey to the mathematical property that 
+
+    a^b == (a+1)^(b+1)
+
+one-third of the time.  So don't do that.
+  
 =item stat FILEHANDLE
 
 =item stat EXPR
@@ -3090,6 +3207,9 @@ 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>.
 
+The IO::File module provides a more object-oriented approach, if you're
+into that kind of thing.
+
 =item sysread FILEHANDLE,SCALAR,LENGTH,OFFSET
 
 =item sysread FILEHANDLE,SCALAR,LENGTH
@@ -3116,9 +3236,42 @@ Note that argument processing varies depending on the number of
 arguments.  The return value is the exit status of the program as
 returned by the wait() call.  To get the actual exit value divide by
 256.  See also L</exec>.  This is I<NOT> what you want to use to capture 
-the output from a command, for that you should use merely back-ticks, as
-described in L<perlop/"`STRING`">.
+the output from a command, for that you should use merely back-ticks or
+qx//, as described in L<perlop/"`STRING`">.
 
+Because system() and back-ticks block SIGINT and SIGQUIT, killing the
+program they're running doesn't actually interrupt your program.
+
+    @args = ("command", "arg1", "arg2");
+    system(@args) == 0 
+        or die "system @args failed: $?" 
+
+Here's a more elaborate example of analysing the return value from
+system() on a UNIX system to check for all possibilities, including for
+signals and coredumps.
+
+    $rc = 0xffff & system @args;
+    printf "system(%s) returned %#04x: ", "@args", $rc;
+    if ($rc == 0) {
+       print "ran with normal exit\n";
+    } 
+    elsif ($rc == 0xff00) {
+       print "command failed: $!\n";
+    } 
+    elsif ($rc > 0x80) {
+       $rc >>= 8;
+       print "ran with non-zero exit status $rc\n";
+    } 
+    else {
+       print "ran with ";
+       if ($rc &   0x80) {
+           $rc &= ~0x80;
+           print "coredump from ";
+       } 
+       print "signal $rc\n"
+    } 
+    $ok = ($rc != 0);
+  
 =item syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET
 
 =item syswrite FILEHANDLE,SCALAR,LENGTH
@@ -3243,7 +3396,7 @@ on your system.
 
 Returns an uppercased version of EXPR.  This is the internal function
 implementing the \U escape in double-quoted strings.
-Should respect any POSIX setlocale() settings.
+Respects current LC_CTYPE locale if C<use locale> in force.  See L<perllocale>.
 
 If EXPR is omitted, uses $_.
 
@@ -3253,7 +3406,7 @@ If EXPR is omitted, uses $_.
 
 Returns the value of EXPR with the first character uppercased.  This is
 the internal function implementing the \u escape in double-quoted strings.
-Should respect any POSIX setlocale() settings.
+Respects current LC_CTYPE locale if C<use locale> in force.  See L<perllocale>.
 
 If EXPR is omitted, uses $_.