X-Git-Url: https://perl5.git.perl.org/perl5.git/blobdiff_plain/c69ca1d4c45d8f9405e06ad3419c8ab43c8ae1d0..904028df2142182d347e16fc663545daf1b31fd8:/pod/perlfunc.pod diff --git a/pod/perlfunc.pod b/pod/perlfunc.pod index ec265b1..94bc8d7 100644 --- a/pod/perlfunc.pod +++ b/pod/perlfunc.pod @@ -12,7 +12,7 @@ following comma. (See the precedence table in L.) List operators take more than one argument, while unary operators can never take more than one argument. Thus, a comma terminates the argument of a unary operator, but merely separates the arguments of a list -operator. A unary operator generally provides a scalar context to its +operator. A unary operator generally provides scalar context to its argument, while a list operator may provide either scalar or list contexts for its arguments. If it does both, scalar arguments come first and list argument follow, and there can only ever @@ -55,8 +55,8 @@ and C. For example, C always means C. For functions that can be used in either a scalar or list context, -nonabortive failure is generally indicated in a scalar context by -returning the undefined value, and in a list context by returning the +nonabortive failure is generally indicated in scalar context by +returning the undefined value, and in list context by returning the empty list. Remember the following important rule: There is B that relates @@ -79,10 +79,10 @@ there, not the list construction version of the comma. That means it was never a list to start with. In general, functions in Perl that serve as wrappers for system calls ("syscalls") -of the same name (like chown(2), fork(2), closedir(2), etc.) all return +of the same name (like chown(2), fork(2), closedir(2), etc.) return true when they succeed and C otherwise, as is usually mentioned in the descriptions below. This is different from the C interfaces, -which return C<-1> on failure. Exceptions to this rule are C, +which return C<-1> on failure. Exceptions to this rule include C, C, and C. System calls also set the special C<$!> variable on failure. Other functions do not, except accidentally. @@ -146,7 +146,7 @@ C, C, C, C, C, C and low-level POSIX tty-handling operations. If FILEHANDLE is an expression, the value is taken as an indirect filehandle, generally its name. @@ -1931,25 +2002,21 @@ same underlying descriptor: print "THIS and THAT are dups\n"; } -(Filehandles connected to memory objects via new features of C may -return undefined even though they are open.) - - =item flock FILEHANDLE,OPERATION X X X Calls flock(2), or an emulation of it, on FILEHANDLE. Returns true for success, false on failure. Produces a fatal error if used on a machine that doesn't implement flock(2), fcntl(2) locking, or lockf(3). -C is Perl's portable file locking interface, although it locks +C is Perl's portable file-locking interface, although it locks entire files only, not records. Two potentially non-obvious but traditional C semantics are that it waits indefinitely until the lock is granted, and that its locks -B. Such discretionary locks are more flexible, but offer -fewer guarantees. This means that programs that do not also use C -may modify files locked with C. See L, -your port's specific documentation, or your system-specific local manpages +are B. Such discretionary locks are more flexible, but +offer fewer guarantees. This means that programs that do not also use +C may modify files locked with C. See L, +your port's specific documentation, and your system-specific local manpages for details. It's best to assume traditional behavior if you're writing portable programs. (But if you're not, you should as always feel perfectly free to write for your own system's idiosyncrasies (sometimes called @@ -1958,11 +2025,11 @@ in the way of your getting your job done.) 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 import them from the Fcntl module, -either individually, or as a group using the ':flock' tag. LOCK_SH +you can use the symbolic names if you import them from the L module, +either individually, or as a group using the C<:flock> tag. LOCK_SH requests a shared lock, LOCK_EX requests an exclusive lock, and LOCK_UN releases a previously requested lock. If LOCK_NB is bitwise-or'ed with -LOCK_SH or LOCK_EX then C returns immediately rather than blocking +LOCK_SH or LOCK_EX, then C returns immediately rather than blocking waiting for the lock; check the return status to see if you got it. To avoid the possibility of miscoordination, Perl now flushes FILEHANDLE @@ -1983,7 +2050,7 @@ network; you would need to use the more system-specific C 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 program when you configure -Perl. +and build a new Perl. Here's a mailbox appender for BSD systems. @@ -2015,6 +2082,8 @@ function lose their locks, making it seriously harder to write servers. See also L for other flock() examples. +Portability issues: L. + =item fork X X X @@ -2044,6 +2113,14 @@ if you exit, then the remote server (such as, say, a CGI script or a backgrounded job launched from a remote shell) won't think you're done. You should reopen those to F if it's any issue. +On some platforms such as Windows, where the fork() system call is not available, +Perl can be built to emulate fork() in the Perl interpreter. The emulation is designed to, +at the level of the Perl program, be as compatible as possible with the "Unix" fork(). +However it has limitations that have to be considered in code intended to be portable. +See L for more details. + +Portability issues: L. + =item format X @@ -2082,6 +2159,10 @@ Be careful if you put double quotes around the picture, because an C<@> character may be taken to mean the beginning of an array name. C always returns true. See L for other examples. +If you are trying to use this instead of C to capture the output, +you may find it easier to open a filehandle to a scalar +(C<< open $fh, ">", \$output >>) and write to that instead. + =item getc FILEHANDLE X X X X @@ -2116,7 +2197,7 @@ is left as an exercise to the reader. The C function can do this more portably on systems purporting POSIX compliance. See also the C -module from your nearest CPAN site; details on CPAN can be found on +module from your nearest CPAN site; details on CPAN can be found under L. =item getlogin @@ -2131,10 +2212,13 @@ returns the empty string, use C. Do not consider C for authentication: it is not as secure as C. +Portability issues: L. + =item getpeername SOCKET X X -Returns the packed sockaddr address of other end of the SOCKET connection. +Returns the packed sockaddr address of the other end of the SOCKET +connection. use Socket; $hersockaddr = getpeername(SOCK); @@ -2148,10 +2232,12 @@ X X Returns the current process group for the specified PID. Use a PID of C<0> to get the current process group for the current process. Will raise an exception if used on a machine that -doesn't implement getpgrp(2). If PID is omitted, returns process -group of current process. Note that the POSIX version of C +doesn't implement getpgrp(2). If PID is omitted, returns the process +group of the current process. Note that the POSIX version of C does not accept a PID argument, so only C is truly portable. +Portability issues: L. + =item getppid X X X @@ -2164,13 +2250,17 @@ C, that returns a consistent value across threads. If you want to call the underlying C, you may use the CPAN module C. +Portability issues: L. + =item getpriority WHICH,WHO X X X Returns the current priority for a process, a process group, or a user. -(See C.) Will raise a fatal exception if used on a +(See L.) Will raise a fatal exception if used on a machine that doesn't implement getpriority(2). +Portability issues: L. + =item getpwnam NAME X X X X X X X X X X @@ -2257,7 +2347,7 @@ information pertaining to the user. Beware, however, that in many system users are able to change this information and therefore it cannot be trusted and therefore the $gcos is tainted (see L). The $passwd and $shell, user's encrypted password and -login shell, are also tainted, because of the same reason. +login shell, are also tainted, for the same reason. In scalar context, you get the name, unless the function was a lookup by name, in which case you get the other thing, whatever it is. @@ -2281,7 +2371,7 @@ field may be $change or $age, fields that have to do with password aging. In some systems the $comment field may be $class. The $expire field, if present, encodes the expiration period of the account or the password. For the availability and the exact meaning of these fields -in your system, please consult your getpwnam(3) documentation and your +in your system, please consult getpwnam(3) and your system's F file. You can also find out from within Perl what your $quota and $comment fields mean and whether you have the $expire field by using the C module and the values C, C, @@ -2290,10 +2380,10 @@ files are supported only if your vendor has implemented them in the intuitive fashion that calling the regular C library routines gets the shadow versions if you're running under privilege or if there exists the shadow(3) functions as found in System V (this includes Solaris -and Linux.) Those systems that implement a proprietary shadow password +and Linux). Those systems that implement a proprietary shadow password facility are unlikely to be supported. -The $members value returned by I is a space separated list of +The $members value returned by I is a space-separated list of the login names of the members of the group. For the I functions, if the C variable is supported in @@ -2338,10 +2428,12 @@ for each field. For example: use User::pwent; $is_his = (stat($filename)->uid == pwent($whoever)->uid); -Even though it looks like they're the same method calls (uid), +Even though it looks as though they're the same method calls (uid), they aren't, because a C object is different from a C object. +Portability issues: L to L. + =item getsockname SOCKET X @@ -2370,12 +2462,12 @@ number of TCP, which you can get using C. The function returns a packed string representing the requested socket option, or C on error, with the reason for the error placed in -C<$!>). Just what is in the packed string depends on LEVEL and OPTNAME; +C<$!>. Just what is in the packed string depends on LEVEL and OPTNAME; consult getsockopt(2) for details. A common case is that the option is an integer, in which case the result is a packed integer, which you can decode using C with the C (or C) format. -An example to test whether Nagle's algorithm is turned on on a socket: +Here's an example to test whether Nagle's algorithm is enabled on a socket: use Socket qw(:all); @@ -2387,6 +2479,31 @@ An example to test whether Nagle's algorithm is turned on on a socket: my $nodelay = unpack("I", $packed); print "Nagle's algorithm is turned ", $nodelay ? "off\n" : "on\n"; +Portability issues: L. + +=item given EXPR BLOCK +X + +=item given BLOCK + +C is analogous to the C keyword in other languages. C +and C are used in Perl to implement C/C like statements. +Only available after Perl 5.10. For example: + + use v5.10; + given ($fruit) { + when (/apples?/) { + print "I like apples." + } + when (/oranges?/) { + print "I don't like oranges." + } + default { + print "I don't like anything" + } + } + +See L for detailed information. =item glob EXPR X X X X @@ -2417,19 +2534,21 @@ Beginning with v5.6.0, this operator is implemented using the standard C extension. See L for details, including C which does not treat whitespace as a pattern separator. +Portability issues: L. + =item gmtime EXPR X X X =item gmtime -Works just like L but the returned values are +Works just like L but the returned values are localized for the standard Greenwich time zone. -Note: when called in list context, $isdst, the last value -returned by gmtime is always C<0>. There is no +Note: When called in list context, $isdst, the last value +returned by gmtime, is always C<0>. There is no Daylight Saving Time in GMT. -See L for portability concerns. +Portability issues: L. =item goto LABEL X X X @@ -2454,6 +2573,10 @@ necessarily recommended if you're optimizing for maintainability: goto ("FOO", "BAR", "GLARCH")[$i]; +As shown in this example, C is exempt from the "looks like a +function" rule. A pair of parentheses following it does not (necessarily) +delimit its argument. C is equivalent to C. + Use of C or C to jump into a construct is deprecated and will issue a warning. Even then, it may not be used to go into any construct that requires initialization, such as a @@ -2473,7 +2596,7 @@ After the C, not even C will be able to tell that this routine was called first. NAME needn't be the name of a subroutine; it can be a scalar variable -containing a code reference, or a block that evaluates to a code +containing a code reference or a block that evaluates to a code reference. =item grep BLOCK LIST @@ -2526,7 +2649,7 @@ L.) If EXPR is omitted, uses C<$_>. Hex strings may only represent integers. Strings that would cause integer overflow trigger a warning. Leading whitespace is not stripped, unlike oct(). To present something as hex, look into L, -L, or L. +L, and L. =item import LIST X @@ -2602,6 +2725,8 @@ system: The special string C<"0 but true"> is exempt from B<-w> complaints about improper numeric conversions. +Portability issues: L. + =item join EXPR,LIST X @@ -2613,10 +2738,12 @@ separated by the value of EXPR, and returns that new string. Example: Beware that unlike C, C doesn't take a pattern as its first argument. Compare L. -=item keys HASH (or HASHREF) +=item keys HASH X X -=item keys ARRAY (or ARRAYREF) +=item keys ARRAY + +=item keys EXPR Returns a list consisting of all the keys of the named hash, or the indices of an array. (In scalar context, returns the number of keys or indices.) @@ -2629,7 +2756,7 @@ Perl 5.8.1 the ordering can be different even between different runs of Perl for security reasons (see L). -As a side effect, calling keys() resets the HASH or ARRAY's internal iterator +As a side effect, calling keys() resets the internal interator of the HASH or ARRAY (see L). In particular, calling keys() in void context resets the iterator with no other overhead. @@ -2673,18 +2800,15 @@ C in this way (but you needn't worry about doing this by accident, as trying has no effect). C in an lvalue context is a syntax error. -When given a reference to a hash or array, the argument will be -dereferenced automatically. +Starting with Perl 5.14, C can take a scalar EXPR, which must contain +a reference to an unblessed hash or array. The argument will be +dereferenced automatically. This aspect of C is considered highly +experimental. The exact behaviour may change in a future version of Perl. for (keys $hashref) { ... } for (keys $obj->get_arrayref) { ... } -If the reference is a blessed object that overrides either C<%{}> or -C<@{}>, the override will be used instead of dereferencing the underlying -variable type. If both overrides are provided, C<%{}> will be the default. -If this is not desired, you must dereference the argument yourself. - -See also C, C and C. +See also C, C, and C. =item kill SIGNAL, LIST X X @@ -2713,6 +2837,15 @@ signal the current process group and -1 will signal all processes. See L for more details. +On some platforms such as Windows where the fork() system call is not available. +Perl can be built to emulate fork() at the interpreter level. +This emulation has limitations related to kill that have to be considered, +for code running on Windows and in code intended to be portable. + +See L for more details. + +Portability issues: L. + =item last LABEL X X @@ -2729,7 +2862,7 @@ C block, if any, is not executed: } C cannot be used to exit a block that returns a value such as -C, C or C, and should not be used to exit +C, C, or C, and should not be used to exit a grep() or map() operation. Note that a block by itself is semantically identical to a loop @@ -2771,7 +2904,8 @@ respectively. =item Otherwise, If EXPR has the UTF8 flag set If the current package has a subroutine named C, it will be used to -change the case (See L.) +change the case +(See L.) Otherwise Unicode semantics are used for the case change. =item Otherwise, if C is in effect @@ -2781,7 +2915,7 @@ Respects current LC_CTYPE locale. See L. =item Otherwise, if C is in effect: Unicode semantics are used for the case change. Any subroutine named -C will not be used. +C will be ignored. =item Otherwise: @@ -2811,7 +2945,7 @@ double-quoted strings. If EXPR is omitted, uses C<$_>. -This function behaves the same way under various pragma, such as in a locale, +This function behaves the same way under various pragmata, such as in a locale, as L does. =item length EXPR @@ -2820,7 +2954,8 @@ X X =item length Returns the length in I of the value of EXPR. If EXPR is -omitted, returns length of C<$_>. If EXPR is undefined, returns C. +omitted, returns the length of C<$_>. If EXPR is undefined, returns +C. This function cannot be used on an entire array or hash to find out how many elements these have. For that, use C and C Creates a new filename linked to the old filename. Returns true for success, false otherwise. +Portability issues: L. + =item listen SOCKET,QUEUESIZE X @@ -2873,19 +3010,19 @@ follows: ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time); -All list elements are numeric, and come straight out of the C `struct +All list elements are numeric and come straight out of the C `struct tm'. C<$sec>, C<$min>, and C<$hour> are the seconds, minutes, and hours of the specified time. -C<$mday> is the day of the month, and C<$mon> is the month itself, in -the range C<0..11> with 0 indicating January and 11 indicating December. +C<$mday> is the day of the month and C<$mon> the month in +the range C<0..11>, with 0 indicating January and 11 indicating December. This makes it easy to get a month name from a list: my @abbr = qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec ); print "$abbr[$mon] $mday"; # $mon=9, $mday=18 gives "Oct 18" -C<$year> is the number of years since 1900, not just the last two digits +C<$year> is the number of years since 1900, B just the last two digits of the year. That is, C<$year> is C<123> in year 2023. The proper way to get a 4-digit year is simply: @@ -2894,7 +3031,7 @@ to get a 4-digit year is simply: Otherwise you create non-Y2K-compliant programs--and you wouldn't want to do that, would you? -To get the last two digits of the year (e.g., '01' in 2001) do: +To get the last two digits of the year (e.g., "01" in 2001) do: $year = sprintf("%02d", $year % 100); @@ -2912,13 +3049,13 @@ In scalar context, C returns the ctime(3) value: $now_string = localtime; # e.g., "Thu Oct 13 04:54:34 1994" -This scalar value is B locale dependent but is a Perl builtin. For GMT +This scalar value is B locale-dependent but is a Perl builtin. For GMT instead of local time use the L builtin. See also the -C module (to convert the second, minutes, hours, ... back to +C module (for converting seconds, minutes, hours, and such back to the integer value returned by time()), and the L module's strftime(3) and mktime(3) functions. -To get somewhat similar but locale dependent date strings, set up your +To get somewhat similar but locale-dependent date strings, set up your locale environment variables appropriately (please see L) and try for example: @@ -2930,21 +3067,24 @@ try for example: Note that the C<%a> and C<%b>, the short forms of the day of the week and the month of the year, may not necessarily be three characters wide. -See L for portability concerns. - -The L and L modules provides a convenient, +The L and L modules provide a convenient, by-name access mechanism to the gmtime() and localtime() functions, respectively. For a comprehensive date and time representation look at the L module on CPAN. +Portability issues: L. + =item lock THING X -This function places an advisory lock on a shared variable, or referenced +This function places an advisory lock on a shared variable or referenced object contained in I until the lock goes out of scope. +The value returned is the scalar itself, if the argument is a scalar, or a +reference, if the argument is a hash or array. + lock() is a "weak keyword" : this means that if you've defined a function by this name (before any calls to it), that function will be called instead. If you are not under C this does nothing. @@ -2956,7 +3096,8 @@ X X X X X =item log Returns the natural logarithm (base I) of EXPR. If EXPR is omitted, -returns log of C<$_>. To get the log of another base, use basic algebra: +returns the log of C<$_>. To get the +log of another base, use basic algebra: The base-N log of a number is equal to the natural log of that number divided by the natural log of N. For example: @@ -2980,6 +3121,8 @@ information, please see the documentation for C. If EXPR is omitted, stats C<$_>. +Portability issues: L. + =item m// The match operator. See L. @@ -2996,9 +3139,27 @@ total number of elements so generated. Evaluates BLOCK or EXPR in list context, so each element of LIST may produce zero, one, or more elements in the returned value. - @chars = map(chr, @nums); + @chars = map(chr, @numbers); + +translates a list of numbers to the corresponding characters. + + my @squares = map { $_ * $_ } @numbers; + +translates a list of numbers to their squared values. + + my @squares = map { $_ > 5 ? ($_ * $_) : () } @numbers; + +shows that number of returned elements can differ from the number of +input elements. To omit an element, return an empty list (). +This could also be achieved by writing -translates a list of numbers to the corresponding characters. And + my @squares = map { $_ * $_ } grep { $_ > 5 } @numbers; + +which makes the intention more clear. + +Map always returns a list, which can be +assigned to a hash such that the elements +become key/value pairs. See L for more details. %hash = map { get_a_key_for($_) => $_ } @array; @@ -3053,12 +3214,12 @@ X X X Creates the directory specified by FILENAME, with permissions specified by MASK (as modified by C). If it succeeds it -returns true, otherwise it returns false and sets C<$!> (errno). -If omitted, MASK defaults to 0777. If omitted, FILENAME defaults -to C<$_>. +returns true; otherwise it returns false and sets C<$!> (errno). +MASK defaults to 0777 if omitted, and FILENAME defaults +to C<$_> if omitted. -In general, it is better to create directories with permissive MASK, -and let the user modify that with their C, than it is to supply +In general, it is better to create directories with a permissive MASK +and let the user modify that with their C than it is to supply a restrictive MASK and give the user no way to be more permissive. The exceptions to this rule are when the file or directory should be kept private (mail files, for instance). The perlfunc(1) entry on @@ -3083,14 +3244,20 @@ first to get the correct constant definitions. If CMD is C, then ARG must be a variable that will hold the returned C structure. Returns like C: the undefined value for error, C<"0 but true"> for zero, or the actual return value otherwise. See also -L, C, and C documentation. +L and the documentation for C and +C. + +Portability issues: L. =item msgget KEY,FLAGS X Calls the System V IPC function msgget(2). Returns the message queue -id, or the undefined value if there is an error. See also -L and C and C documentation. +id, or C on error. See also +L and the documentation for C and +C. + +Portability issues: L. =item msgrcv ID,VAR,SIZE,TYPE,FLAGS X @@ -3100,21 +3267,25 @@ message queue ID into variable VAR with a maximum message size of SIZE. Note that when a message is received, the message type as a native long integer will be the first thing in VAR, followed by the actual message. This packing may be opened with C. -Taints the variable. Returns true if successful, or false if there is -an error. See also L, C, and -C documentation. +Taints the variable. Returns true if successful, false +on error. See also L and the documentation for +C and C. + +Portability issues: L. =item msgsnd ID,MSG,FLAGS X Calls the System V IPC function msgsnd to send the message MSG to the message queue ID. MSG must begin with the native long integer message -type, and be followed by the length of the actual message, and finally +type, be followed by the length of the actual message, and then finally the message itself. This kind of packing can be achieved with C. Returns true if successful, -or false if there is an error. See also C +false on error. See also the C and C documentation. +Portability issues: L. + =item my EXPR X @@ -3129,7 +3300,7 @@ enclosing block, file, or C. If more than one value is listed, the list must be placed in parentheses. The exact semantics and interface of TYPE and ATTRS are still -evolving. TYPE is currently bound to the use of C pragma, +evolving. TYPE is currently bound to the use of the C pragma, and attributes are handled using the C pragma, or starting from Perl 5.8.0 also via the C module. See L for details, and L, @@ -3153,7 +3324,7 @@ executed even on discarded lines. If LABEL is omitted, the command refers to the innermost enclosing loop. C cannot be used to exit a block which returns a value such as -C, C or C, and should not be used to exit +C, C, or C, and should not be used to exit a grep() or map() operation. Note that a block by itself is semantically identical to a loop @@ -3221,67 +3392,66 @@ FILEHANDLE. Simple examples to open a file for reading: - open(my $fh, '<', "input.txt") or die $!; + open(my $fh, "<", "input.txt") + or die "cannot open < input.txt: $!"; and for writing: - open(my $fh, '>', "output.txt") or die $!; + open(my $fh, ">", "output.txt") + or die "cannot open > output.txt: $!"; (The following is a comprehensive reference to open(): for a gentler introduction you may consider L.) -If FILEHANDLE is an undefined scalar variable (or array or hash element) -the variable is assigned a reference to a new anonymous filehandle, -otherwise if FILEHANDLE is an expression, its value is used as the name of -the real filehandle wanted. (This is considered a symbolic reference, so -C should I be in effect.) - -If EXPR is omitted, the scalar variable of the same name as the -FILEHANDLE contains the filename. (Note that lexical variables--those -declared with C--will not work for this purpose; so if you're -using C, specify EXPR in your call to open.) - -If three or more arguments are specified then the mode of opening and -the filename are separate. If MODE is C<< '<' >> or nothing, the file -is opened for input. If MODE is C<< '>' >>, the file is truncated and -opened for output, being created if necessary. If MODE is C<<< '>>' >>>, -the file is opened for appending, again being created if necessary. - -You can put a C<'+'> in front of the C<< '>' >> or C<< '<' >> to +If FILEHANDLE is an undefined scalar variable (or array or hash element), a +new filehandle is autovivified, meaning that the variable is assigned a +reference to a newly allocated anonymous filehandle. Otherwise if +FILEHANDLE is an expression, its value is the real filehandle. (This is +considered a symbolic reference, so C should I be +in effect.) + +If EXPR is omitted, the global (package) scalar variable of the same +name as the FILEHANDLE contains the filename. (Note that lexical +variables--those declared with C or C--will not work for this +purpose; so if you're using C or C, specify EXPR in your +call to open.) + +If three (or more) arguments are specified, the open mode (including +optional encoding) in the second argument are distinct from the filename in +the third. If MODE is C<< < >> or nothing, the file is opened for input. +If MODE is C<< > >>, the file is opened for output, with existing files +first being truncated ("clobbered") and nonexisting files newly created. +If MODE is C<<< >> >>>, the file is opened for appending, again being +created if necessary. + +You can put a C<+> in front of the C<< > >> or C<< < >> to indicate that you want both read and write access to the file; thus -C<< '+<' >> is almost always preferred for read/write updates--the -C<< '+>' >> mode would clobber the file first. You can't usually use +C<< +< >> is almost always preferred for read/write updates--the +C<< +> >> mode would clobber the file first. You cant usually use either read-write mode for updating textfiles, since they have -variable length records. See the B<-i> switch in L for a +variable-length records. See the B<-i> switch in L for a better approach. The file is created with permissions of C<0666> modified by the process's C value. -These various prefixes correspond to the fopen(3) modes of C<'r'>, -C<'r+'>, C<'w'>, C<'w+'>, C<'a'>, and C<'a+'>. - -In the two-argument (and one-argument) form of the call, the mode and -filename should be concatenated (in that order), possibly separated by -spaces. You may omit the mode in these forms when that mode is -C<< '<' >>. +These various prefixes correspond to the fopen(3) modes of C, +C, C, C, C, and C. -If the filename begins with C<'|'>, the filename is interpreted as a -command to which output is to be piped, and if the filename ends with a -C<'|'>, the filename is interpreted as a command that pipes output to -us. See L -for more examples of this. (You are not allowed to C to a command -that pipes both in I out, but see L, L, -and L -for alternatives.) +In the one- and two-argument forms of the call, the mode and filename +should be concatenated (in that order), preferably separated by white +space. You can--but shouldn't--omit the mode in these forms when that mode +is C<< < >>. It is always safe to use the two-argument form of C if +the filename argument is a known literal. -For three or more arguments if MODE is C<'|-'>, the filename is +For three or more arguments if MODE is C<|->, the filename is interpreted as a command to which output is to be piped, and if MODE -is C<'-|'>, the filename is interpreted as a command that pipes +is C<-|>, the filename is interpreted as a command that pipes output to us. In the two-argument (and one-argument) form, one should -replace dash (C<'-'>) with the command. +replace dash (C<->) with the command. See L for more examples of this. (You are not allowed to C to a command that pipes both in I out, but see L, L, and -L for alternatives.) +L for +alternatives.) In the form of pipe opens taking three or more arguments, if LIST is specified (extra arguments after the command name) then LIST becomes arguments @@ -3290,18 +3460,18 @@ C with more than three arguments for non-pipe modes is not yet defined, but experimental "layers" may give extra LIST arguments meaning. -In the two-argument (and one-argument) form, opening C<< '<-' >> -or C<'-'> opens STDIN and opening C<< '>-' >> opens STDOUT. +In the two-argument (and one-argument) form, opening C<< <- >> +or C<-> opens STDIN and opening C<< >- >> opens STDOUT. -You may use the three-argument form of open to specify I/O layers -(sometimes referred to as "disciplines") to apply to the handle +You may (and usually should) use the three-argument form of open to specify +I/O layers (sometimes referred to as "disciplines") to apply to the handle that affect how the input and output are processed (see L and L for more details). For example: open(my $fh, "<:encoding(UTF-8)", "filename") || die "can't open UTF-8 encoded filename: $!"; -opens the UTF-8 encoded file containing Unicode characters; +opens the UTF8-encoded file containing Unicode characters; see L. Note that if layers are specified in the three-argument form, then default layers stored in ${^OPEN} (see L; usually set by the B pragma or the switch B<-CioD>) are ignored. @@ -3325,43 +3495,44 @@ where you want to format a suitable error message (but there are modules that can help with that problem)) always check the return value from opening a file. -As a special case the 3-arg form with a read/write mode and the third +As a special case the three-argument form with a read/write mode and the third argument being C: open(my $tmp, "+>", undef) or die ... -opens a filehandle to an anonymous temporary file. Also using "+<" +opens a filehandle to an anonymous temporary file. Also using C<< +< >> works for symmetry, but you really should consider writing something to the temporary file first. You will need to seek() to do the reading. Since v5.8.0, Perl has built using PerlIO by default. Unless you've -changed this (i.e., Configure -Uuseperlio), you can open filehandles -directly to Perl scalars via: +changed this (such as building Perl with C), you can +open filehandles directly to Perl scalars via: - open($fh, '>', \$variable) || .. + open($fh, ">", \$variable) || .. To (re)open C or C as an in-memory file, close it first: close STDOUT; - open STDOUT, '>', \$variable or die "Can't open STDOUT: $!"; + open(STDOUT, ">", \$variable) + or die "Can't open STDOUT: $!"; General examples: $ARTICLE = 100; - open ARTICLE or die "Can't find article $ARTICLE: $!\n"; + open(ARTICLE) or die "Can't find article $ARTICLE: $!\n"; while (
) {... - open(LOG, '>>/usr/spool/news/twitlog'); # (log is reserved) + open(LOG, ">>/usr/spool/news/twitlog"); # (log is reserved) # if the open fails, output is discarded - open(my $dbase, '+<', 'dbase.mine') # open for update + open(my $dbase, "+<", "dbase.mine") # open for update or die "Can't open 'dbase.mine' for update: $!"; - open(my $dbase, '+', \$var) + open(MEMORY, ">", \$var) or die "Can't open memory file: $!"; print MEMORY "foo!\n"; # output will appear in $var # process argument list of files along with any includes foreach $file (@ARGV) { - process($file, 'fh00'); + process($file, "fh00"); } sub process { my($filename, $input) = @_; $input++; # this is a string increment - unless (open($input, $filename)) { + unless (open($input, "<", $filename)) { print STDERR "Can't open $filename: $!\n"; return; } @@ -3402,24 +3573,24 @@ General examples: See L for detailed info on PerlIO. You may also, in the Bourne shell tradition, specify an EXPR beginning -with C<< '>&' >>, in which case the rest of the string is interpreted +with C<< >& >>, in which case the rest of the string is interpreted as the name of a filehandle (or file descriptor, if numeric) to be duped (as C) and opened. You may use C<&> after C<< > >>, C<<< >> >>>, C<< < >>, C<< +> >>, C<<< +>> >>>, and C<< +< >>. The mode you specify should match the mode of the original filehandle. (Duping a filehandle does not take into account any existing contents -of IO buffers.) If you use the 3-arg form then you can pass either a -number, the name of a filehandle or the normal "reference to a glob". +of IO buffers.) If you use the three-argument form, then you can pass either a +number, the name of a filehandle, or the normal "reference to a glob". Here is a script that saves, redirects, and restores C and C using various methods: #!/usr/bin/perl - open my $oldout, ">&STDOUT" or die "Can't dup STDOUT: $!"; - open OLDERR, ">&", \*STDERR or die "Can't dup STDERR: $!"; + open(my $oldout, ">&STDOUT") or die "Can't dup STDOUT: $!"; + open(OLDERR, ">&", \*STDERR) or die "Can't dup STDERR: $!"; - open STDOUT, '>', "foo.out" or die "Can't redirect STDOUT: $!"; - open STDERR, ">&STDOUT" or die "Can't dup STDOUT: $!"; + open(STDOUT, '>', "foo.out") or die "Can't redirect STDOUT: $!"; + open(STDERR, ">&STDOUT") or die "Can't dup STDOUT: $!"; select STDERR; $| = 1; # make unbuffered select STDOUT; $| = 1; # make unbuffered @@ -3427,8 +3598,8 @@ C using various methods: print STDOUT "stdout 1\n"; # this works for print STDERR "stderr 1\n"; # subprocesses too - open STDOUT, ">&", $oldout or die "Can't dup \$oldout: $!"; - open STDERR, ">&OLDERR" or die "Can't dup OLDERR: $!"; + open(STDOUT, ">&", $oldout) or die "Can't dup \$oldout: $!"; + open(STDERR, ">&OLDERR") or die "Can't dup OLDERR: $!"; print STDOUT "stdout 2\n"; print STDERR "stderr 2\n"; @@ -3457,26 +3628,47 @@ or Being parsimonious on filehandles is also useful (besides being parsimonious) for example when something is dependent on file descriptors, like for example locking using flock(). If you do just -C<< open(A, '>>&B') >>, the filehandle A will not have the same file -descriptor as B, and therefore flock(A) will not flock(B), and vice -versa. But with C<< open(A, '>>&=B') >> the filehandles will share -the same file descriptor. - -Note that if you are using Perls older than 5.8.0, Perl will be using -the standard C libraries' fdopen() to implement the "=" functionality. -On many Unix systems fdopen() fails when file descriptors exceed a -certain value, typically 255. For Perls 5.8.0 and later, PerlIO is -most often the default. - -You can see whether Perl has been compiled with PerlIO or not by -running C and looking for C line. If C -is C, you have PerlIO, otherwise you don't. - -If you open a pipe on the command C<'-'>, i.e., either C<'|-'> or C<'-|'> -with 2-arguments (or 1-argument) form of open(), then -there is an implicit fork done, and the return value of open is the pid -of the child within the parent process, and C<0> within the child -process. (Use C to determine whether the open was successful.) +C<< open(A, ">>&B") >>, the filehandle A will not have the same file +descriptor as B, and therefore flock(A) will not flock(B) nor vice +versa. But with C<< open(A, ">>&=B") >>, the filehandles will share +the same underlying system file descriptor. + +Note that under Perls older than 5.8.0, Perl uses the standard C library's' +fdopen() to implement the C<=> functionality. On many Unix systems, +fdopen() fails when file descriptors exceed a certain value, typically 255. +For Perls 5.8.0 and later, PerlIO is (most often) the default. + +You can see whether your Perl was built with PerlIO by running C +and looking for the C line. If C is C, you +have PerlIO; otherwise you don't. + +If you open a pipe on the command C<-> (that is, specify either C<|-> or C<-|> +with the one- or two-argument forms of C), +an implicit C is done, so C returns twice: in the parent +process it returns the pid +of the child process, and in the child process it returns (a defined) C<0>. +Use C or C to determine whether the open was successful. + +For example, use either + + $child_pid = open(FROM_KID, "-|") // die "can't fork: $!"; + +or + $child_pid = open(TO_KID, "|-") // die "can't fork: $!"; + +followed by + + if ($child_pid) { + # am the parent: + # either write TO_KID or else read FROM_KID + ... + wait $child_pid; + } else { + # am the child; use STDIN/STDOUT normally + ... + exit; + } + 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 @@ -3488,19 +3680,26 @@ you don't want to have to scan shell commands for metacharacters. The following blocks are more or less equivalent: open(FOO, "|tr '[a-z]' '[A-Z]'"); - open(FOO, '|-', "tr '[a-z]' '[A-Z]'"); - open(FOO, '|-') || exec 'tr', '[a-z]', '[A-Z]'; - open(FOO, '|-', "tr", '[a-z]', '[A-Z]'); + open(FOO, "|-", "tr '[a-z]' '[A-Z]'"); + open(FOO, "|-") || exec 'tr', '[a-z]', '[A-Z]'; + open(FOO, "|-", "tr", '[a-z]', '[A-Z]'); open(FOO, "cat -n '$file'|"); - open(FOO, '-|', "cat -n '$file'"); - open(FOO, '-|') || exec 'cat', '-n', $file; - open(FOO, '-|', "cat", '-n', $file); + open(FOO, "-|", "cat -n '$file'"); + open(FOO, "-|") || exec "cat", "-n", $file; + open(FOO, "-|", "cat", "-n", $file); -The last two examples in each block shows the pipe as "list form", which is +The last two examples in each block show the pipe as "list form", which is not yet supported on all platforms. A good rule of thumb is that if -your platform has true C (in other words, if your platform is -Unix) you can use the list form. +your platform has a real C (in other words, if your platform is +Unix, including Linux and MacOS X), you can use the list form. You would +want to use the list form of the pipe so you can pass literal arguments +to the command without risk of the shell interpreting any shell metacharacters +in them. However, this also bars you from opening pipes to commands +that intentionally contain shell metacharacters, such as: + + open(FOO, "|cat -n | expand -4 | lpr") + // die "Can't open pipeline to lpr: $!"; See L for more examples of this. @@ -3512,14 +3711,14 @@ of C on any open handles. On systems that support a close-on-exec flag on files, the flag will be set for the newly opened file descriptor as determined by the value -of $^F. See L. +of C<$^F>. See L. Closing any piped filehandle causes the parent process to wait for the -child to finish, and returns the status value in C<$?> and +child to finish, then returns the status value in C<$?> and C<${^CHILD_ERROR_NATIVE}>. -The filename passed to 2-argument (or 1-argument) form of open() will -have leading and trailing whitespace deleted, and the normal +The filename passed to the one- and two-argument forms of open() will +have leading and trailing whitespace deleted and normal redirection characters honored. This property, known as "magic open", can often be used to good effect. A user could specify a filename of F<"rsh cat file |">, or you could change certain filenames as needed: @@ -3527,33 +3726,36 @@ F<"rsh cat file |">, or you could change certain filenames as needed: $filename =~ s/(.*\.gz)\s*$/gzip -dc < $1|/; open(FH, $filename) or die "Can't open $filename: $!"; -Use 3-argument form to open a file with arbitrary weird characters in it, +Use the three-argument form to open a file with arbitrary weird characters in it, - open(FOO, '<', $file); + open(FOO, "<", $file) + || die "can't open < $file: $!"; otherwise it's necessary to protect any leading and trailing whitespace: $file =~ s#^(\s)#./$1#; - open(FOO, "< $file\0"); + open(FOO, "< $file\0") + || die "open failed: $!"; (this may not work on some bizarre filesystems). One should -conscientiously choose between the I and 3-arguments form +conscientiously choose between the I and I form of open(): - open IN, $ARGV[0]; + open(IN, $ARGV[0]) || die "can't open $ARGV[0]: $!"; will allow the user to specify an argument of the form C<"rsh cat file |">, but will not work on a filename that happens to have a trailing space, while - open IN, '<', $ARGV[0]; + open(IN, "<", $ARGV[0]) + || die "can't open < $ARGV[0]: $!"; will have exactly the opposite restrictions. -If you want a "real" C C (see C on your system), then you -should use the C function, which involves no such magic (but -may use subtly different filemodes than Perl open(), which is mapped -to C fopen()). This is -another way to protect your filenames from interpretation. For example: +If you want a "real" C C (see L on your system), then you +should use the C function, which involves no such magic (but may +use subtly different filemodes than Perl open(), which is mapped to C +fopen()). This is another way to protect your filenames from +interpretation. For example: use IO::Handle; sysopen(HANDLE, $path, O_RDWR|O_CREAT|O_EXCL) @@ -3565,24 +3767,36 @@ another way to protect your filenames from interpretation. For example: Using the constructor from the C package (or one of its subclasses, such as C or C), you can generate anonymous -filehandles that have the scope of whatever variables hold references to -them, and automatically close whenever and however you leave that scope: +filehandles that have the scope of the variables used to hold them, then +automatically (but silently) close once their reference counts become +zero, typically at scope exit: use IO::File; #... sub read_myfile_munged { my $ALL = shift; + # or just leave it undef to autoviv my $handle = IO::File->new; - open($handle, "myfile") or die "myfile: $!"; + 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. + mung($first) or die "mung failed"; # Or here. + return (first, <$handle>) if $ALL; # Or here. + return $first; # Or here. } +B The previous example has a bug because the automatic +close that happens when the refcount on C does not +properly detect and report failures. I close the handle +yourself and inspect the return value. + + close($handle) + || warn "close failed: $!"; + See L for some details about mixing reading and writing. +Portability issues: L. + =item opendir DIRHANDLE,EXPR X @@ -3591,10 +3805,10 @@ C, C, and C. Returns true if successful. DIRHANDLE may be an expression whose value can be used as an indirect dirhandle, usually the real dirhandle name. If DIRHANDLE is an undefined scalar variable (or array or hash element), the variable is assigned a -reference to a new anonymous dirhandle. +reference to a new anonymous dirhandle; that is, it's autovivified. DIRHANDLEs have their own namespace separate from FILEHANDLEs. -See example at C. +See the example at C. =item ord EXPR X X @@ -3602,8 +3816,9 @@ X X =item ord Returns the numeric (the native 8-bit encoding, like ASCII or EBCDIC, -or Unicode) value of the first character of EXPR. If EXPR is an empty -string, returns 0. If EXPR is omitted, uses C<$_>. +or Unicode) value of the first character of EXPR. +If EXPR is an empty string, returns 0. If EXPR is omitted, uses C<$_>. +(Note I, not byte.) For the reverse, see L. See L for more about Unicode. @@ -3621,14 +3836,14 @@ C associates a simple name with a package variable in the current package for use within the current scope. When C is in effect, C lets you use declared global variables without qualifying them with package names, within the lexical scope of the C declaration. -In this way C differs from C, which is package scoped. +In this way C differs from C, which is package-scoped. -Unlike C, which both allocates storage for a variable and associates -a simple name with that storage for use within the current scope, C -associates a simple name with a package variable in the current package, -for use within the current scope. In other words, C has the same -scoping rules as C, but does not necessarily create a -variable. +Unlike C or C, which allocates storage for a variable and +associates a simple name with that storage for use within the current +scope, C associates a simple name with a package (read: global) +variable in the current package, for use within the current lexical scope. +In other words, C has the same scoping rules as C or C, but +does not necessarily create a variable. If more than one value is listed, the list must be placed in parentheses. @@ -3848,7 +4063,7 @@ packed string. =item * And if it's an integer I, the offset is relative to the start of the -Ith innermost C<()> group, or to the start of the string if I is +Ith innermost C<( )> group, or to the start of the string if I is bigger then the group level. =back @@ -3862,17 +4077,18 @@ count should not be more than 65. The C, C, and C types gobble just one value, but pack it as a string of length count, padding with nulls or spaces as needed. When unpacking, C strips trailing whitespace and nulls, C strips everything -after the first null, and C returns data without any sort of trimming. +after the first null, and C returns data with no stripping at all. If the value to pack is too long, the result is truncated. If it's too long and an explicit count is provided, C packs only C<$count-1> bytes, followed by a null byte. Thus C always packs a trailing null, except -for when the count is 0. +when the count is 0. =item * Likewise, the C and C formats pack a string that's that many bits long. -Each such format generates 1 bit of the result. +Each such format generates 1 bit of the result. These are typically followed +by a repeat count like C or C. Each result bit is based on the least-significant bit of the corresponding input character, i.e., on C. In particular, characters C<"0"> @@ -3891,21 +4107,21 @@ at the end. Similarly during unpacking, "extra" bits are ignored. If the input string is longer than needed, remaining characters are ignored. A C<*> for the repeat count uses all characters of the input field. -On unpacking, bits are converted to a string of C<"0">s and C<"1">s. +On unpacking, bits are converted to a string of C<0>s and C<1>s. =item * The C and C formats pack a string that many nybbles (4-bit groups, representable as hexadecimal digits, C<"0".."9"> C<"a".."f">) long. -For each such format, pack() generates 4 bits of the result. +For each such format, pack() generates 4 bits of result. With non-alphabetical characters, the result is based on the 4 least-significant bits of the input character, i.e., on C. In particular, characters C<"0"> and C<"1"> generate nybbles 0 and 1, as do bytes C<"\000"> and C<"\001">. For characters C<"a".."f"> and C<"A".."F">, the result is compatible with the usual hexadecimal digits, so that C<"a"> and -C<"A"> both generate the nybble C<0xa==10>. Do not use any characters -but these with this format. +C<"A"> both generate the nybble C<0xA==10>. Use only these specific hex +characters with this format. Starting from the beginning of the template to pack(), each pair of characters is converted to 1 character of output. With format C, the @@ -4032,8 +4248,8 @@ handled by the CPU registers) into bytes as Basically, Intel and VAX CPUs are little-endian, while everybody else, including Motorola m68k/88k, PPC, Sparc, HP PA, Power, and Cray, are -big-endian. Alpha and MIPS can be either: Digital/Compaq used/uses them in -little-endian mode, but SGI/Cray uses them in big-endian mode. +big-endian. Alpha and MIPS can be either: Digital/Compaq uses (well, used) +them in little-endian mode, but SGI/Cray uses them in big-endian mode. The names I and I are comic references to the egg-eating habits of the little-endian Lilliputians and the big-endian @@ -4073,10 +4289,10 @@ Starting with Perl 5.9.2, integer and floating-point formats, along with the C

and C

formats and C<()> groups, may all be followed by the C<< > >> or C<< < >> endianness modifiers to respectively enforce big- or little-endian byte-order. These modifiers are especially useful -given how C, C, C and C don't cover signed integers, +given how C, C, C, and C don't cover signed integers, 64-bit integers, or floating-point values. -Here are some concerns to keep in mind when using endianness modifier: +Here are some concerns to keep in mind when using an endianness modifier: =over @@ -4140,6 +4356,26 @@ starts with C. You can always switch mode mid-format with an explicit C or C in the format. This mode remains in effect until the next mode change, or until the end of the C<()> group it (directly) applies to. +Using C to get Unicode characters while using C to get I-Unicode +bytes is not necessarily obvious. Probably only the first of these +is what you want: + + $ perl -CS -E 'say "\x{3B1}\x{3C9}"' | + perl -CS -ne 'printf "%v04X\n", $_ for unpack("C0A*", $_)' + 03B1.03C9 + $ perl -CS -E 'say "\x{3B1}\x{3C9}"' | + perl -CS -ne 'printf "%v02X\n", $_ for unpack("U0A*", $_)' + CE.B1.CF.89 + $ perl -CS -E 'say "\x{3B1}\x{3C9}"' | + perl -C0 -ne 'printf "%v02X\n", $_ for unpack("C0A*", $_)' + CE.B1.CF.89 + $ perl -CS -E 'say "\x{3B1}\x{3C9}"' | + perl -C0 -ne 'printf "%v02X\n", $_ for unpack("U0A*", $_)' + C3.8E.C2.B1.C3.8F.C2.89 + +Those examples also illustrate that you should not try to use +C/C as a substitute for the L module. + =item * You must yourself do any alignment or padding by inserting, for example, @@ -4195,7 +4431,7 @@ for complicated pattern matches. =item * -If TEMPLATE requires more arguments that pack() is given, pack() +If TEMPLATE requires more arguments than pack() is given, pack() assumes additional C<""> arguments. If TEMPLATE requires fewer arguments than given, extra arguments are ignored. @@ -4271,27 +4507,30 @@ Examples: The same template may generally also be used in unpack(). +=item package NAMESPACE + =item package NAMESPACE VERSION X X X X -=item package NAMESPACE +=item package NAMESPACE BLOCK =item package NAMESPACE VERSION BLOCK X X X X -=item package NAMESPACE BLOCK - -Declares the BLOCK, or the rest of the compilation unit, as being in -the given namespace. The scope of the package declaration is either the +Declares the BLOCK or the rest of the compilation unit as being in the +given namespace. The scope of the package declaration is either the supplied code BLOCK or, in the absence of a BLOCK, from the declaration -itself through the end of the enclosing block, file, or eval (the same -as the C operator). All unqualified dynamic identifiers in this -scope will be in the given namespace, except where overridden by another -C declaration. +itself through the end of current scope (the enclosing block, file, or +C). That is, the forms without a BLOCK are operative through the end +of the current scope, just like the C, C, and C operators. +All unqualified dynamic identifiers in this scope will be in the given +namespace, except where overridden by another C declaration or +when they're one of the special identifiers that qualify into C, +like C, C, C, and the punctuation variables. A package statement affects dynamic variables only, including those you've used C on, but I lexical variables, which are created -with C (or C (or C)). Typically it would be the first +with C, C, or C. Typically it would be the first declaration in a file included by C or C. You can switch into a package in more than one place, since this only determines which default symbol table the compiler uses for the rest of that block. You can refer to @@ -4321,16 +4560,19 @@ unless you are very careful. In addition, note that Perl's pipes use IO buffering, so you may need to set C<$|> to flush your WRITEHANDLE after each command, depending on the application. -See L, L, and L +See L, L, and +L for examples of such things. On systems that support a close-on-exec flag on files, that flag is set on all newly opened file descriptors whose Cs are I than the current value of $^F (by default 2 for C). See L. -=item pop ARRAY (or ARRAYREF) +=item pop ARRAY X X +=item pop EXPR + =item pop Pops and returns the last value of the array, shortening the array by @@ -4340,8 +4582,10 @@ Returns the undefined value if the array is empty, although this may also happen at other times. If ARRAY is omitted, pops the C<@ARGV> array in the main program, but the C<@_> array in subroutines, just like C. -If given a reference to an array, the argument will be dereferenced -automatically. +Starting with Perl 5.14, C can take a scalar EXPR, which must hold a +reference to an unblessed array. The argument will be dereferenced +automatically. This aspect of C is considered highly experimental. +The exact behaviour may change in a future version of Perl. =item pos SCALAR X X @@ -4361,6 +4605,9 @@ expressions. Both of these effects take place for the next match, so you can't affect the position with C during the current match, such as in C<(?{pos() = 5})> or C. +Setting C also resets the I flag, described +under L. + Because a failed C match doesn't reset the offset, the return from C won't change either in this case. See L and L. @@ -4368,34 +4615,38 @@ L. =item print FILEHANDLE LIST X +=item print FILEHANDLE + =item print LIST =item print Prints a string or a list of strings. Returns true if successful. -FILEHANDLE may be a scalar variable containing -the name of or a reference to 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 C<+> or put parentheses around the arguments.) -If FILEHANDLE is omitted, prints to standard output by default, or -to the last selected output channel; see L. If LIST is -also omitted, prints C<$_> to the currently selected output handle. -To set the default output handle to something other than STDOUT -use the select operation. The current value of C<$,> (if any) is -printed between each LIST item. The current value of C<$\> (if -any) is printed after the entire LIST has been printed. Because -print takes a LIST, anything in the LIST is evaluated in list -context, and any subroutine that you call will have one or more of -its expressions evaluated in list 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; put parentheses around all the arguments +FILEHANDLE may be a scalar variable containing the name of or a reference +to 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 C<+> or put +parentheses around the arguments.) If FILEHANDLE is omitted, prints to the +last selected (see L) output handle. If LIST is omitted, prints +C<$_> to the currently selected output handle. To use FILEHANDLE alone to +print the content of C<$_> to it, you must use a real filehandle like +C, not an indirect one like C<$fh>. To set the default output handle +to something other than STDOUT, use the select operation. + +The current value of C<$,> (if any) is printed between each LIST item. The +current value of C<$\> (if any) is printed after the entire LIST has been +printed. Because print takes a LIST, anything in the LIST is evaluated in +list context, including any subroutines whose return lists you pass to +C. 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; put parentheses around all arguments (or interpose a C<+>, but that doesn't look as good). -Note that if you're storing FILEHANDLEs in an array, or if you're using -any other expression more complex than a scalar variable to retrieve it, -you will have to use a block returning the filehandle value instead: +If you're storing handles in an array or hash, or in general whenever +you're using any expression more complex than a bareword handle or a plain, +unsubscripted scalar variable to retrieve it, you will have to use a block +returning the filehandle value instead, in which case the LIST may not be +omitted: print { $files[$i] } "stuff\n"; print { $OK ? STDOUT : STDERR } "stuff\n"; @@ -4406,15 +4657,22 @@ L for more on signal handling. =item printf FILEHANDLE FORMAT, LIST X +=item printf FILEHANDLE + =item printf FORMAT, LIST +=item printf + Equivalent to C, except that C<$\> -(the output record separator) is not appended. The first argument -of the list will be interpreted as the C format. See C -for an explanation of the format argument. If C is in effect, -and POSIX::setlocale() has been called, the character used for the decimal +(the output record separator) is not appended. The first argument of the +list will be interpreted as the C format. See +L for an +explanation of the format argument. If you omit the LIST, C<$_> is used; +to use FILEHANDLE without a LIST, you must use a real filehandle like +C, not an indirect one like C<$fh>. If C is in effect and +POSIX::setlocale() has been called, the character used for the decimal separator in formatted floating-point numbers is affected by the LC_NUMERIC -locale. See L and L. +locale setting. See L and L. Don't fall into the trap of using a C when a simple C would do. The C is more efficient and less @@ -4434,12 +4692,14 @@ C) or if its arguments cannot be adequately expressed by a prototype does not really behave like a Perl function. Otherwise, the string describing the equivalent prototype is returned. -=item push ARRAY (or ARRAYREF),LIST +=item push ARRAY,LIST X X -Treats ARRAY 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 +=item push EXPR,LIST + +Treats ARRAY as a stack by appending the values of LIST to 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; @@ -4448,8 +4708,10 @@ LIST. Has the same effect as but is more efficient. Returns the number of elements in the array following the completed C. -If given a reference to an array, the argument will be dereferenced -automatically. +Starting with Perl 5.14, C can take a scalar EXPR, which must hold a +reference to an unblessed array. The argument will be dereferenced +automatically. This aspect of C is considered highly experimental. +The exact behaviour may change in a future version of Perl. =item q/STRING/ @@ -4502,8 +4764,13 @@ Or: my $quoted_substring = quotemeta($substring); $sentence =~ s{$quoted_substring}{big bad wolf}; -Will both leave the sentence as is. Normally, when accepting string input from -the user, quotemeta() or C<\Q> must be used. +Will both leave the sentence as is. Normally, when accepting literal string +input from the user, quotemeta() or C<\Q> must be used. + +In Perl 5.14, all characters whose code points are above 127 are not +quoted in UTF8-encoded strings, but all are quoted in UTF-8 strings. +It is planned to change this behavior in 5.16, but the exact rules +haven't been determined yet. =item rand EXPR X X @@ -4528,6 +4795,13 @@ returns a random integer between C<0> and C<9>, inclusive. large or too small, then your version of Perl was probably compiled with the wrong number of RANDBITS.) +B is not cryptographically secure. You should not rely +on it in security-sensitive situations.> As of this writing, a +number of third-party CPAN modules offer random number generators +intended by their authors to be cryptographically secure, +including: L, L, and +L. + =item read FILEHANDLE,SCALAR,LENGTH,OFFSET X X @@ -4548,13 +4822,14 @@ results in the string being padded to the required size with C<"\0"> bytes before the result of the read is appended. The call is implemented in terms of either Perl's or your system's native -fread(3) library function. To get a true read(2) system call, see C. +fread(3) library function. To get a true read(2) system call, see +L. Note the I: depending on the status of the filehandle, -either (8-bit) bytes or characters are read. By default all +either (8-bit) bytes or characters are read. By default, all filehandles operate on bytes, but for example if the filehandle has been opened with the C<:utf8> I/O layer (see L, and the C -pragma, L), the I/O will operate on UTF-8 encoded Unicode +pragma, L), the I/O will operate on UTF8-encoded Unicode characters, not bytes. Similarly for the C<:encoding> pragma: in that case pretty much any characters can be read. @@ -4589,7 +4864,7 @@ which will set C<$_> on every iteration. X X X Reads from the filehandle whose typeglob is contained in EXPR (or from -*ARGV if EXPR is not provided). In scalar context, each call reads and +C<*ARGV> if EXPR is not provided). In scalar context, each call reads and returns the next line until end-of-file is reached, whereupon the subsequent call returns C. In list context, reads until end-of-file is reached and returns a list of lines. Note that the notion of "line" @@ -4642,6 +4917,8 @@ implemented. If not, raises an exception. If there is a system error, returns the undefined value and sets C<$!> (errno). If EXPR is omitted, uses C<$_>. +Portability issues: L. + =item readpipe EXPR =item readpipe @@ -4673,7 +4950,7 @@ Note the I: depending on the status of the socket, either (8-bit) bytes or characters are received. By default all sockets operate on bytes, but for example if the socket has been changed using binmode() to operate with the C<:encoding(utf8)> I/O layer (see the -C pragma, L), the I/O will operate on UTF-8 encoded Unicode +C pragma, L), the I/O will operate on UTF8-encoded Unicode characters, not bytes. Similarly for the C<:encoding> pragma: in that case pretty much any characters can be read. @@ -4706,7 +4983,7 @@ normally use this command: } C cannot be used to retry a block that returns a value such as -C, C or C, and should not be used to exit +C, C, or C, and should not be used to exit a grep() or map() operation. Note that a block by itself is semantically identical to a loop @@ -4775,6 +5052,8 @@ rename(2) manpage or equivalent system documentation for details. For a platform independent C function look at the L module. +Portability issues: L. + =item require VERSION X @@ -4875,9 +5154,9 @@ first look for a similar filename with a "F<.pmc>" extension. If this file is found, it will be loaded in place of any file ending in a "F<.pm>" extension. -You can also insert hooks into the import facility, by putting Perl code +You can also insert hooks into the import facility by putting Perl code directly into the @INC array. There are three forms of hooks: subroutine -references, array references and blessed objects. +references, array references, and blessed objects. Subroutine references are the simplest case. When the inclusion system walks through @INC and encounters a subroutine, this subroutine gets @@ -4896,8 +5175,8 @@ A filehandle, from which the file will be read. A reference to a subroutine. If there is no filehandle (previous item), then this subroutine is expected to generate one line of source code per -call, writing the line into C<$_> and returning 1, then returning 0 at -end of file. If there is a filehandle, then the subroutine will be +call, writing the line into C<$_> and returning 1, then finally at end of +file returning 0. If there is a filehandle, then the subroutine will be called to act as a simple source filter, with the line as read in C<$_>. Again, return 1 for each valid line, and 0 after all lines have been returned. @@ -4912,8 +5191,8 @@ reference to the subroutine itself is passed in as C<$_[0]>. If an empty list, C, or nothing that matches the first 3 values above is returned, then C looks at the remaining elements of @INC. Note that this filehandle must be a real filehandle (strictly a typeglob -or reference to a typeglob, blessed or unblessed); tied filehandles will be -ignored and return value processing will stop there. +or reference to a typeglob, whether blessed or unblessed); tied filehandles +will be ignored and processing will stop there. If the hook is an array reference, its first element must be a subroutine reference. This subroutine is called as above, but the first parameter is @@ -4991,7 +5270,7 @@ X Returns from a subroutine, C, or C with the value given in EXPR. Evaluation of EXPR may be in list, scalar, or void context, depending on how the return value will be used, and the context -may vary from one execution to the next (see C). If no EXPR +may vary from one execution to the next (see L). If no EXPR is given, returns an empty list in list context, the undefined value in scalar context, and (of course) nothing at all in void context. @@ -5035,6 +5314,8 @@ X Sets the current position to the beginning of the directory for the C routine on DIRHANDLE. +Portability issues: L. + =item rindex STR,SUBSTR,POSITION X @@ -5050,7 +5331,7 @@ X X X =item rmdir Deletes the directory specified by FILENAME if that directory is -empty. If it succeeds it returns true, otherwise it returns false and +empty. If it succeeds it returns true; otherwise it returns false and sets C<$!> (errno). If FILENAME is omitted, uses C<$_>. To remove a directory tree recursively (C on Unix) look at @@ -5063,16 +5344,21 @@ The substitution operator. See L. =item say FILEHANDLE LIST X +=item say FILEHANDLE + =item say LIST =item say -Just like C, but implicitly appends a newline. -C is simply an abbreviation for C<{ local $\ = "\n"; print -LIST }>. +Just like C, but implicitly appends a newline. C is +simply an abbreviation for C<{ local $\ = "\n"; print LIST }>. To use +FILEHANDLE without a LIST to print the contents of C<$_> to it, you must +use a real filehandle like C, not an indirect one like C<$fh>. -This keyword is available only when the "say" feature is -enabled: see L. +This keyword is available only when the C<"say"> feature +is enabled, or when prefixed with C; see +L. Alternately, include a C or later to the current +scope. =item scalar EXPR X X @@ -5088,10 +5374,10 @@ needed. If you really wanted to do so, however, you could use the construction C<@{[ (some expression) ]}>, but usually a simple C<(some expression)> suffices. -Because C is a unary operator, if you accidentally use for EXPR a -parenthesized list, this behaves as a scalar comma expression, evaluating -all but the last element in void context and returning the final element -evaluated in scalar context. This is seldom what you want. +Because C is a unary operator, if you accidentally use a +parenthesized list for the EXPR, this behaves as a scalar comma expression, +evaluating all but the last element in void context and returning the final +element evaluated in scalar context. This is seldom what you want. The following single statement: @@ -5110,11 +5396,11 @@ X X X Sets FILEHANDLE's position, just like the C call of C. FILEHANDLE may be an expression whose value gives the name of the filehandle. The values for WHENCE are C<0> to set the new position -I to POSITION, C<1> to set it to the current position plus -POSITION, and C<2> to set it to EOF plus POSITION (typically -negative). For WHENCE you may use the constants C, +I to POSITION; C<1> to set it to the current position plus +POSITION; and C<2> to set it to EOF plus POSITION, typically +negative. For WHENCE you may use the constants C, C, and C (start of the file, current position, end -of the file) from the Fcntl module. Returns C<1> on success, C<0> +of the file) from the L module. Returns C<1> on success, false otherwise. Note the I: even if the filehandle has been set to @@ -5166,11 +5452,12 @@ X @@ -5195,22 +5484,22 @@ This calls the select(2) syscall with the bit masks specified, which can be constructed using C and C, along these lines: $rin = $win = $ein = ''; - vec($rin,fileno(STDIN),1) = 1; - vec($win,fileno(STDOUT),1) = 1; + vec($rin, fileno(STDIN), 1) = 1; + vec($win, fileno(STDOUT), 1) = 1; $ein = $rin | $win; If you want to select on many filehandles, you may wish to write a subroutine like this: sub fhbits { - my(@fhlist) = split(' ',$_[0]); - my($bits); - for (@fhlist) { - vec($bits,fileno($_),1) = 1; + my @fhlist = @_; + my $bits = ""; + for my $fh (@fhlist) { + vec($bits, fileno($fh), 1) = 1; } - $bits; + return $bits; } - $rin = fhbits('STDIN TTY SOCK'); + $rin = fhbits(*STDIN, *TTY, *MYSOCK); The usual idiom is: @@ -5237,19 +5526,23 @@ Note that whether C. -On error, C behaves just like select(2): it returns -1 and sets C<$!>. -On some Unixes, select(2) may report a socket file -descriptor as "ready for reading" when no data is available, and -thus a subsequent read blocks. This can be avoided if you always use -O_NONBLOCK on the socket. See select(2) and fcntl(2) for further -details. +On some Unixes, select(2) may report a socket file descriptor as "ready for +reading" even when no data is available, and thus any subsequent C +would block. This can be avoided if you always use O_NONBLOCK on the +socket. See select(2) and fcntl(2) for further details. + +The standard C module provides a user-friendlier interface +to C, except as permitted by POSIX, and even then only on POSIX systems. You have to use C instead. +Portability issues: L. + =item semctl ID,SEMNUM,CMD,ARG X @@ -5266,14 +5559,18 @@ short integers, which may be created with C. See also L, C, C documentation. +Portability issues: L. + =item semget KEY,NSEMS,FLAGS X Calls the System V IPC function semget(2). Returns the semaphore id, or -the undefined value if there is an error. See also +the undefined value on error. See also L, C, C documentation. +Portability issues: L. + =item semop KEY,OPSTRING X @@ -5282,7 +5579,7 @@ such as signalling and waiting. OPSTRING must be a packed array of semop structures. Each semop structure can be generated with C. The length of OPSTRING implies the number of semaphore operations. Returns true if -successful, or false if there is an error. As an example, the +successful, false on error. As an example, the following code waits on semaphore $semnum of semaphore id $semid: $semop = pack("s!3", $semnum, -1, 0); @@ -5292,6 +5589,8 @@ To signal the semaphore, replace C<-1> with C<1>. See also L, C, and C documentation. +Portability issues: L. + =item send SOCKET,MSG,FLAGS,TO X @@ -5322,6 +5621,8 @@ it defaults to C<0,0>. Note that the BSD 4.2 version of C does not accept any arguments, so only C is portable. See also C. +Portability issues: L. + =item setpriority WHICH,WHO,PRIORITY X X X X @@ -5329,11 +5630,13 @@ Sets the current priority for a process, a process group, or a user. (See setpriority(2).) Raises an exception when used on a machine that doesn't implement setpriority(2). +Portability issues: L. + =item setsockopt SOCKET,LEVEL,OPTNAME,OPTVAL X -Sets the socket option requested. Returns undefined if there is an -error. Use integer constants provided by the C module for +Sets the socket option requested. Returns C on error. +Use integer constants provided by the C module for LEVEL and OPNAME. Values for LEVEL can also be obtained from getprotobyname. OPTVAL might either be a packed string or an integer. An integer OPTVAL is shorthand for pack("i", OPTVAL). @@ -5343,9 +5646,13 @@ An example disabling Nagle's algorithm on a socket: use Socket qw(IPPROTO_TCP TCP_NODELAY); setsockopt($socket, IPPROTO_TCP, TCP_NODELAY, 1); -=item shift ARRAY (or ARRAYREF) +Portability issues: L. + +=item shift ARRAY X +=item shift EXPR + =item shift Shifts the first value of the array off and returns it, shortening the @@ -5354,10 +5661,12 @@ array, returns the undefined value. If ARRAY is omitted, shifts the C<@_> array within the lexical scope of subroutines and formats, and the C<@ARGV> array outside a subroutine and also within the lexical scopes established by the C, C, C, C, -C and C constructs. +C, and C constructs. -If given a reference to an array, the argument will be dereferenced -automatically. +Starting with Perl 5.14, C can take a scalar EXPR, which must hold a +reference to an unblessed array. The argument will be dereferenced +automatically. This aspect of C is considered highly experimental. +The exact behaviour may change in a future version of Perl. See also C, C, and C. C and C do the same thing to the left end of an array that C and C do to the @@ -5372,17 +5681,21 @@ Calls the System V IPC function shmctl. You'll probably have to say first to get the correct constant definitions. If CMD is C, then ARG must be a variable that will hold the returned C -structure. Returns like ioctl: the undefined value for error, "C<0> but -true" for zero, or the actual return value otherwise. +structure. Returns like ioctl: C for error; "C<0> but +true" for zero; and the actual return value otherwise. See also L and C documentation. +Portability issues: L. + =item shmget KEY,SIZE,FLAGS X Calls the System V IPC function shmget. Returns the shared memory -segment id, or the undefined value if there is an error. +segment id, or C on error. See also L and C documentation. +Portability issues: L. + =item shmread ID,VAR,POS,SIZE X X @@ -5394,9 +5707,11 @@ position POS for size SIZE by attaching to it, copying in/out, and detaching from it. When reading, VAR must be a variable that will hold the data read. When writing, if STRING is too long, only SIZE bytes are used; if STRING is too short, nulls are written to fill out -SIZE bytes. Return true if successful, or false if there is an error. +SIZE bytes. Return true if successful, false on error. shmread() taints the variable. See also L, -C documentation, and the C module from CPAN. +C, and the C module from CPAN. + +Portability issues: L and L. =item shutdown SOCKET,HOW X @@ -5502,6 +5817,8 @@ See L for an example of socketpair use. Perl 5.8 and later will emulate socketpair using IP sockets to localhost if your system implements sockets but not socketpair. +Portability issues: L. + =item sort SUBNAME LIST X X X X @@ -5522,13 +5839,12 @@ the value provides the name of (or a reference to) the actual subroutine to use. In place of a SUBNAME, you can provide a BLOCK as an anonymous, in-line sort subroutine. -If the subroutine's prototype is C<($$)>, the elements to be compared -are passed by reference in C<@_>, as for a normal subroutine. This is -slower than unprototyped subroutines, where the elements to be -compared are passed into the subroutine -as the package global variables $a and $b (see example below). Note that -in the latter case, it is usually counter-productive to declare $a and -$b as lexicals. +If the subroutine's prototype is C<($$)>, the elements to be compared are +passed by reference in C<@_>, as for a normal subroutine. This is slower +than unprototyped subroutines, where the elements to be compared are passed +into the subroutine as the package global variables $a and $b (see example +below). Note that in the latter case, it is usually highly counter-productive +to declare $a and $b as lexicals. The values to be compared are always passed by reference and should not be modified. @@ -5546,7 +5862,7 @@ actually modifies the element in the original list. This is usually something to be avoided when writing clear code. Perl 5.6 and earlier used a quicksort algorithm to implement sort. -That algorithm was not stable, and I go quadratic. (A I sort +That algorithm was not stable, so I go quadratic. (A I sort preserves the input order of elements that compare equal. Although quicksort's run time is O(NlogN) when averaged over all arrays of length N, the time can be O(N**2), I behavior, for some @@ -5682,22 +5998,22 @@ sometimes saying the opposite, for example) the results are not well-defined. Because C<< <=> >> returns C when either operand is C -(not-a-number), and because C raises an exception unless the -result of a comparison is defined, when sorting with a comparison function -like C<< $a <=> $b >>, be careful about lists that might contain a C. -The following example takes advantage that C to +(not-a-number), and laso because C raises an exception unless the +result of a comparison is defined, be careful when sorting with a +comparison function like C<< $a <=> $b >> any lists that might contain a +C. The following example takes advantage that C to eliminate any Cs from the input list. @result = sort { $a <=> $b } grep { $_ == $_ } @input; -=item splice ARRAY (or ARRAYREF),OFFSET,LENGTH,LIST +=item splice ARRAY or EXPR,OFFSET,LENGTH,LIST X -=item splice ARRAY (or ARRAYREF),OFFSET,LENGTH +=item splice ARRAY or EXPR,OFFSET,LENGTH -=item splice ARRAY (or ARRAYREF),OFFSET +=item splice ARRAY or EXPR,OFFSET -=item splice ARRAY (or ARRAYREF) +=item splice ARRAY or EXPR Removes the elements designated by OFFSET and LENGTH from an array, and replaces them with the elements of LIST, if any. In list context, @@ -5712,9 +6028,6 @@ If both OFFSET and LENGTH are omitted, removes everything. If OFFSET is past the end of the array, Perl issues a warning, and splices at the end of the array. -If given a reference to an array, the argument will be dereferenced -automatically. - The following equivalences hold (assuming C<< $[ == 0 and $#a >= $i >> ) push(@a,$x,$y) splice(@a,@a,0,$x,$y) @@ -5736,6 +6049,11 @@ Example, assuming array lengths are passed before arrays: } if (&aeq($len,@foo[1..$len],0+@bar,@bar)) { ... } +Starting with Perl 5.14, C can take scalar EXPR, which must hold a +reference to an unblessed array. The argument will be dereferenced +automatically. This aspect of C is considered highly experimental. +The exact behaviour may change in a future version of Perl. + =item split /PATTERN/,EXPR,LIMIT X @@ -5862,7 +6180,7 @@ X Returns a string formatted by the usual C conventions of the C library function C. See below for more details -and see C or C on your system for an explanation of +and see L or L on your system for an explanation of the general principles. For example: @@ -6006,11 +6324,11 @@ display the given value. You can override the width by putting a number here, or get the width from the next argument (with C<*>) or from a specified argument (e.g., with C<*2$>): - printf '<%s>', "a"; # prints "" - printf '<%6s>', "a"; # prints "< a>" - printf '<%*s>', 6, "a"; # prints "< a>" - printf '<%*2$s>', "a", 6; # prints "< a>" - printf '<%2s>', "long"; # prints "" (does not truncate) + printf "<%s>", "a"; # prints "" + printf "<%6s>", "a"; # prints "< a>" + printf "<%*s>", 6, "a"; # prints "< a>" + printf "<%*2$s>", "a", 6; # prints "< a>" + printf "<%2s>", "long"; # prints "" (does not truncate) If a field width obtained through C<*> is negative, it has the same effect as the C<-> flag: left-justification. @@ -6020,7 +6338,7 @@ X You can specify a precision (for numeric conversions) or a maximum width (for string conversions) by specifying a C<.> followed by a number. -For floating-point formats except 'g' and 'G', this specifies +For floating-point formats except C and C, this specifies how many places right of the decimal point to show (the default being 6). For example: @@ -6100,15 +6418,30 @@ whatever the default integer size is on your platform (usually 32 or 64 bits), but you can override this to use instead one of the standard C types, as supported by the compiler used to build Perl: - l interpret integer as C type "long" or "unsigned long" + hh interpret integer as C type "char" or "unsigned char" + on Perl 5.14 or later h interpret integer as C type "short" or "unsigned short" - q, L or ll interpret integer as C type "long long", "unsigned long long". - or "quads" (typically 64-bit integers) + j interpret integer as C type "intmax_t" on Perl 5.14 + or later, and only with a C99 compiler (unportable) + l interpret integer as C type "long" or "unsigned long" + q, L, or ll interpret integer as C type "long long", "unsigned long long", + or "quad" (typically 64-bit integers) + t interpret integer as C type "ptrdiff_t" on Perl 5.14 or later + z interpret integer as C type "size_t" on Perl 5.14 or later -The last will raise an exception if Perl does not understand "quads" in your -installation. (This requires either that the platform natively support quads, -or that Perl were specifically compiled to support quads.) You can find out -whether your Perl supports quads via L: +As of 5.14, none of these raises an exception if they are not supported on +your platform. However, if warnings are enabled, a warning of the +C warning class is issued on an unsupported conversion flag. +Should you instead prefer an exception, do this: + + use warnings FATAL => "printf"; + +If you would like to know about a version dependency before you +start running the program, put something like this at its top: + + use 5.014; # for hh/j/t/z/ printf modifiers + +You can find out whether your Perl supports quads via L: use Config; if ($Config{use64bitint} eq "define" || $Config{longsize} >= 8) { @@ -6259,7 +6592,7 @@ one-third of the time. So don't do that. A typical use of the returned seed is for a test program which has too many combinations to test comprehensively in the time available to it each run. It can test a random subset each time, and should there be a failure, log the seed -used for that run so that it can later be used to reproduce the exact results. +used for that run so that it can later be used to reproduce the same results. =item stat FILEHANDLE X X X @@ -6272,7 +6605,7 @@ X X X Returns a 13-element list giving the status info for a file, either the file opened via FILEHANDLE or DIRHANDLE, or named by EXPR. If EXPR is -omitted, it stats C<$_>. Returns the empty list if C fails. Typically +omitted, it stats C<$_> (not C<_>!). Returns the empty list if C fails. Typically used as follows: ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size, @@ -6300,7 +6633,7 @@ meanings of the fields: (*) Not all fields are supported on all filesystem types. Notably, the ctime field is non-portable. In particular, you cannot expect it to be a -"creation time", see L for details. +"creation time"; see L for details. If C is passed the special filehandle consisting of an underline, no stat is done, but the current contents of the stat structure from the @@ -6394,6 +6727,8 @@ See your native chmod(2) and stat(2) documentation for more details about the C constants. To get status info for a symbolic link instead of the target file behind the link, use the C function. +Portability issues: L. + =item state EXPR X @@ -6403,13 +6738,14 @@ X =item state TYPE EXPR : ATTRS -C declares a lexically scoped variable, just like C does. +C declares a lexically scoped variable, just like C. However, those variables will never be reinitialized, contrary to lexical variables that are reinitialized each time their enclosing block is entered. C variables are enabled only when the C pragma -is in effect. See L. +is in effect, unless the keyword is written as C. +See L. =item study SCALAR X @@ -6419,13 +6755,12 @@ X Takes extra time to study SCALAR (C<$_> if unspecified) in anticipation of doing many pattern matches on the string before it is next modified. This may or may not save time, depending on the nature and number of -patterns you are searching on, and on the distribution of character +patterns you are searching and the distribution of character frequencies in the string to be searched; you probably want to compare -run times with and without it to see which runs faster. Those loops +run times with and without it to see which is faster. Those loops that scan for many short constant strings (including the constant -parts of more complex patterns) will benefit most. You may have only -one C active at a time: if you study a different scalar the first -is "unstudied". (The way C works is this: a linked list of every +parts of more complex patterns) will benefit most. +(The way C works is this: a linked list of every character in the string to be searched is made, so we know, for example, where all the C<'k'> characters are. From each search string, the rarest character is selected, based on some static frequency tables @@ -6480,13 +6815,13 @@ X =item sub NAME (PROTO) : ATTRS BLOCK -This is subroutine definition, not a real function I. -Without a BLOCK it's just a forward declaration. Without a NAME, -it's an anonymous function declaration, and does actually return -a value: the CODE ref of the closure you just created. +This is subroutine definition, not a real function I. Without a +BLOCK it's just a forward declaration. Without a NAME, it's an anonymous +function declaration, so does return a value: the CODE ref of the closure +just created. See L and L for details about subroutines and -references, and L and L for more +references; see L and L for more information about attributes. =item substr EXPR,OFFSET,LENGTH,REPLACEMENT @@ -6497,10 +6832,10 @@ X X X X X =item substr EXPR,OFFSET Extracts a substring out of EXPR and returns it. First character is at -offset C<0>, or whatever you've set C<$[> to (but don't do that). +offset C<0> (or whatever you've set C<$[> to (but B<)). If OFFSET is negative (or more precisely, less than C<$[>), starts -that far from the end of the string. If LENGTH is omitted, returns -everything to the end of the string. If LENGTH is negative, leaves that +that far back from the end of the string. If LENGTH is omitted, returns +everything through the end of the string. If LENGTH is negative, leaves that many characters off the end of the string. my $s = "The black cat climbed the green tree"; @@ -6538,7 +6873,7 @@ just as you can with splice(). my $z = substr $s, 14, 7, "jumped from"; # climbed # $s is now "The black cat jumped from the green tree" -Note that the lvalue returned by the 3-arg version of substr() acts as +Note that the lvalue returned by the three-argument version of substr() acts as a 'magic bullet'; each time it is assigned to, it remembers which part of the original string is being modified; for example: @@ -6563,6 +6898,8 @@ use eval: $symlink_exists = eval { symlink("",""); 1 }; +Portability issues: L. + =item syscall NUMBER, LIST X X @@ -6589,30 +6926,32 @@ which in practice should (usually) suffice. Syscall returns whatever value returned by the system call it calls. If the system call fails, C returns C<-1> and sets C<$!> (errno). -Note that some system calls can legitimately return C<-1>. The proper -way to handle such calls is to assign C<$!=0;> before the call and -check the value of C<$!> if syscall returns C<-1>. +Note that some system calls I legitimately return C<-1>. The proper +way to handle such calls is to assign C<$!=0> before the call, then +check the value of C<$!> if C returns C<-1>. There's a problem with C: it returns the file -number of the read end of the pipe it creates. There is no way +number of the read end of the pipe it creates, but there is no way to retrieve the file number of the other end. You can avoid this problem by using C instead. +Portability issues: L. + =item sysopen FILEHANDLE,FILENAME,MODE X =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 function with the parameters -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 real +filehandle wanted; an undefined scalar will be suitably autovivified. This +function calls the underlying operating system's I(2) function with the +parameters FILENAME, MODE, and PERMS. The possible values and flag bits of the MODE parameter are -system-dependent; they are available via the standard module C. -See the documentation of your operating system's C to see which -values and flag bits are available. You may combine several flags +system-dependent; they are available via the standard module C. See +the documentation of your operating system's I(2) syscall to see +which values and flag bits are available. You may combine several flags using the C<|>-operator. Some of the most common values are C for opening the file in @@ -6661,6 +7000,8 @@ library, or perhaps using the POSIX::open() function. See L for a kinder, gentler explanation of opening files. +Portability issues: L. + =item sysread FILEHANDLE,SCALAR,LENGTH,OFFSET X @@ -6696,20 +7037,19 @@ See L, L, and the C pragma, L. =item sysseek FILEHANDLE,POSITION,WHENCE X X -Sets FILEHANDLE's system position in bytes using -lseek(2). FILEHANDLE may be an expression whose value gives the name -of the filehandle. The values for WHENCE are C<0> to set the new -position to POSITION, C<1> to set the it to the current position plus -POSITION, and C<2> to set it to EOF plus POSITION (typically -negative). +Sets FILEHANDLE's system position in bytes using lseek(2). FILEHANDLE may +be an expression whose value gives the name of the filehandle. The values +for WHENCE are C<0> to set the new position to POSITION; C<1> to set the it +to the current position plus POSITION; and C<2> to set it to EOF plus +POSITION, typically negative. Note the I: even if the filehandle has been set to operate on characters (for example by using the C<:encoding(utf8)> I/O layer), tell() will return byte offsets, not character offsets (because implementing that would render sysseek() unacceptably slow). -sysseek() bypasses normal buffered IO, so mixing this with reads (other -than C, for example C<< <> >> or read()) C, C, +sysseek() bypasses normal buffered IO, so mixing it with reads other +than C (for example C<< <> >> or read()) C, C, C, C, or C may cause confusion. For WHENCE, you may also use the constants C, C, @@ -6731,7 +7071,7 @@ X X =item system PROGRAM LIST Does exactly the same thing as C, except that a fork is -done first, and the parent process waits for the child process to +done first and the parent process waits for the child process to exit. Note that argument processing varies depending on the number of arguments. If there is more than one argument in LIST, or if LIST is an array with more than one value, starts the program @@ -6753,7 +7093,7 @@ of C on any open handles. The return value is the exit status of the program as returned by the C call. To get the actual exit value, shift right by eight (see below). See also L. This is I what you want to use to capture -the output from a command, for that you should use merely backticks or +the output from a command; for that you should use merely backticks or C, as described in L. Return value of -1 indicates a failure to start the program or an error of the wait(2) system call (inspect $! for the reason). @@ -6797,6 +7137,8 @@ See L and L for details. Since C does a C and C it may affect a C handler. See L for details. +Portability issues: L. + =item syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET X @@ -6809,7 +7151,7 @@ specified FILEHANDLE, using write(2). If LENGTH is not specified, writes whole SCALAR. It bypasses buffered IO, so mixing this with reads (other than C, C, C, C, C, or C may cause confusion because the perlio and -stdio layers usually buffers data. Returns the number of bytes +stdio layers usually buffer data. Returns the number of bytes actually written, or C if there was an error (in this case the errno variable C<$!> is also set). If the LENGTH is greater than the data available in the SCALAR after the OFFSET, only as much data as is @@ -6820,10 +7162,12 @@ string other than the beginning. A negative OFFSET specifies writing that many characters counting backwards from the end of the string. If SCALAR is of length zero, you can only use an OFFSET of 0. -B: If the filehandle is marked C<:utf8>, Unicode characters +B: If the filehandle is marked C<:utf8>, Unicode characters encoded in UTF-8 are written instead of bytes, and the LENGTH, OFFSET, and -return value of syswrite() are in (UTF-8 encoded Unicode) characters. +return value of syswrite() are in (UTF8-encoded Unicode) characters. The C<:encoding(...)> layer implicitly introduces the C<:utf8> layer. +Alternately, if the handle is not marked with an encoding but you +attempt to write characters with code points over 255, raises an exception. See L, L, and the C pragma, L. =item tell FILEHANDLE @@ -6848,7 +7192,7 @@ tell() on pipes, fifos, and sockets usually returns -1. There is no C function. Use C for that. Do not use tell() (or other buffered I/O operations) on a filehandle -that has been manipulated by sysread(), syswrite() or sysseek(). +that has been manipulated by sysread(), syswrite(), or sysseek(). Those functions ignore the buffering, while tell() does not. =item telldir DIRHANDLE @@ -6968,11 +7312,10 @@ C. On most systems the epoch is 00:00:00 UTC, January 1, 1970; a prominent exception being Mac OS Classic which uses 00:00:00, January 1, 1904 in the current local time zone for its epoch. -For measuring time in better granularity than one second, -you may use either the L module (from CPAN, and starting from -Perl 5.8 part of the standard distribution), or if you have -gettimeofday(2), you may be able to use the C interface of Perl. -See L for details. +For measuring time in better granularity than one second, use the +L module from Perl 5.8 onwards (or from CPAN before then), or, +if you have gettimeofday(2), you may be able to use the C +interface of Perl. See L for details. For date and time processing look at the many related modules on CPAN. For a comprehensive date and time representation look at the @@ -6981,8 +7324,8 @@ L module. =item times X -Returns a four-element list giving the user and system times, in -seconds, for this process and the children of this process. +Returns a four-element list giving the user and system times in +seconds for this process and any exited children of this process. ($user,$system,$cuser,$csystem) = times; @@ -6990,6 +7333,8 @@ In scalar context, C returns C<$user>. Children's times are only included for terminated children. +Portability issues: L. + =item tr/// The transliteration operator. Same as C. See @@ -7002,14 +7347,15 @@ X Truncates the file opened on FILEHANDLE, or named by EXPR, to the specified length. Raises an exception if truncate isn't implemented -on your system. Returns true if successful, the undefined value -otherwise. +on your system. Returns true if successful, C on error. The behavior is undefined if LENGTH is greater than the length of the file. The position in the file of FILEHANDLE is left unchanged. You may want to -call L before writing to the file. +call L before writing to the file. + +Portability issues: L. =item uc EXPR X X X @@ -7054,11 +7400,11 @@ and isn't one of the digits). The C value is such a number representing disabled permissions bits. The permission (or "mode") values you pass C or C are modified by your umask, so even if you tell C to create a file with permissions C<0777>, -if your umask is C<0022> then the file will actually be created with +if your umask is C<0022>, then the file will actually be created with permissions C<0755>. If your C were C<0027> (group can't write; others can't read, write, or execute), then passing -C C<0666> would create a file with mode C<0640> (C<0666 &~ -027> is C<0640>). +C C<0666> would create a file with mode C<0640> (because +C<0666 &~ 027> is C<0640>). Here's some advice: supply a creation mode of C<0666> for regular files (in C) and one of C<0777> for directories (in @@ -7078,6 +7424,8 @@ not trying to restrict access for yourself, returns C. Remember that a umask is a number, usually given in octal; it is I a string of octal digits. See also L, if all you have is a string. +Portability issues: L. + =item undef EXPR X X @@ -7087,7 +7435,7 @@ Undefines the value of EXPR, which must be an lvalue. Use only on a scalar value, an array (using C<@>), a hash (using C<%>), a subroutine (using C<&>), or a typeglob (using C<*>). Saying C will probably not do what you expect on most predefined variables or -DBM list values, so don't do that; see L. Always returns the +DBM list values, so don't do that; see L. Always returns the undefined value. You can omit the EXPR, in which case nothing is undefined, but you still get an undefined value that you could, for instance, return from a subroutine, assign to a variable, or pass as a @@ -7168,7 +7516,7 @@ a % to indicate that you want a -bit checksum of the items instead of the items themselves. Default is a 16-bit checksum. Checksum is calculated by summing numeric values of expanded values (for string fields the sum of -C is taken, for bit fields the sum of zeroes and ones). +C is taken; for bit fields the sum of zeroes and ones). For example, the following computes the same number as the System V sum program: @@ -7199,15 +7547,18 @@ See L for more examples and notes. =item untie VARIABLE X -Breaks the binding between a variable and a package. (See C.) +Breaks the binding between a variable and a package. +(See L.) Has no effect if the variable is not tied. -=item unshift ARRAY (or ARRAYREF),LIST +=item unshift ARRAY,LIST X +=item unshift EXPR,LIST + Does the opposite of a C. Or the opposite of a C, depending on how you look at it. Prepends list to the front of the -array, and returns the new number of elements in the array. +array and returns the new number of elements in the array. unshift(@ARGV, '-e') unless $ARGV[0] =~ /^-/; @@ -7215,8 +7566,10 @@ Note the LIST is prepended whole, not one element at a time, so the prepended elements stay in the same order. Use C to do the reverse. -If given a reference to an array, the argument will be dereferenced -automatically. +Starting with Perl 5.14, C can take a scalar EXPR, which must hold +a reference to an unblessed array. The argument will be dereferenced +automatically. This aspect of C is considered highly +experimental. The exact behaviour may change in a future version of Perl. =item use Module VERSION LIST X X X @@ -7236,6 +7589,7 @@ package. It is exactly equivalent to BEGIN { require Module; Module->import( LIST ); } except that Module I be a bareword. +The importation can be made conditional; see L. In the peculiar C form, VERSION may be either a positive decimal fraction such as 5.006, which will be compared to C<$]>, or a v-string @@ -7322,7 +7676,7 @@ conditionally, this can be done using the L pragma: use if $] < 5.008, "utf8"; use if WANT_WARNINGS, warnings => qw(all); -There's a corresponding C command that unimports meanings imported +There's a corresponding C declaration that unimports meanings imported by C, i.e., it calls C instead of C. It behaves just as C does with VERSION, an omitted or empty LIST, or no unimport method being found. @@ -7332,7 +7686,7 @@ or no unimport method being found. no warnings; Care should be taken when using the C form of C. It is -I meant to be used to assert that the running perl is of a earlier +I meant to be used to assert that the running Perl is of a earlier version than its argument and I to undo the feature-enabling side effects of C. @@ -7344,7 +7698,7 @@ functionality from the command-line. X 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 +files. The first two elements of the list must be the NUMERIC access and modification times, in that order. Returns the number of files successfully changed. The inode change time of each file is set to the current time. For example, this code has the same effect as the @@ -7383,13 +7737,17 @@ files. On systems that don't support futimes(2), passing filehandles raises an exception. Filehandles must be passed as globs or glob references to be recognized; barewords are considered filenames. -=item values HASH (or HASHREF) +Portability issues: L. + +=item values HASH X -=item values ARRAY (or ARRAYREF) +=item values ARRAY + +=item values EXPR Returns a list consisting of all the values of the named hash, or the values -of an array. (In a scalar context, returns the number of values.) +of an array. (In scalar context, returns the number of values.) The values are returned in an apparently random order. The actual random order is subject to change in future versions of Perl, but it @@ -7399,7 +7757,7 @@ function would produce on the same (unmodified) hash. Since Perl for security reasons (see L). As a side effect, calling values() resets the HASH or ARRAY's internal -iterator, +iterator; see L. (In particular, calling values() in void context resets the iterator with no other overhead. Apart from resetting the iterator, C in list context is the same as plain C<@array>. @@ -7407,31 +7765,27 @@ We recommend that you use void context C for this, but reasoned that it taking C out would require more documentation than leaving it in.) - Note that the values are not copied, which means modifying them will modify the contents of the hash: for (values %hash) { s/foo/bar/g } # modifies %hash values for (@hash{keys %hash}) { s/foo/bar/g } # same -When given a reference to a hash or array, the argument will be -dereferenced automatically. +Starting with Perl 5.14, C can take a scalar EXPR, which must hold +a reference to an unblessed hash or array. The argument will be +dereferenced automatically. This aspect of C is considered highly +experimental. The exact behaviour may change in a future version of Perl. for (values $hashref) { ... } for (values $obj->get_arrayref) { ... } -If the reference is a blessed object that overrides either C<%{}> or -C<@{}>, the override will be used instead of dereferencing the underlying -variable type. If both overrides are provided, C<%{}> will be the default. -If this is not desired, you must dereference the argument yourself. - See also C, C, and C. =item vec EXPR,OFFSET,BITS X X X Treats the string in EXPR as a bit vector made up of elements of -width BITS, and returns the value of the element specified by OFFSET +width BITS and returns the value of the element specified by OFFSET as an unsigned integer. BITS therefore specifies the number of bits that are reserved for each element in the bit vector. This must be a power of two from 1 to 32 (or 64, if your platform supports @@ -7678,6 +8032,8 @@ being automatically reaped, as described in L. If you use wait in your handler for $SIG{CHLD} it may accidentally for the child created by qx() or system(). See L for details. +Portability issues: L. + =item waitpid PID,FLAGS X @@ -7703,6 +8059,8 @@ Note that on some systems, a return value of C<-1> could mean that child processes are being automatically reaped. See L for details, and for other examples. +Portability issues: L. + =item wantarray X X @@ -7762,10 +8120,57 @@ warnings (even the so-called mandatory ones). An example: # run-time warnings enabled after here warn "\$foo is alive and $foo!"; # does show up -See L for details on setting C<%SIG> entries, and for more +See L for details on setting C<%SIG> entries and for more examples. See the Carp module for other kinds of warnings using its carp() and cluck() functions. +=item when EXPR BLOCK +X + +=item when BLOCK + +C is analogous to the C keyword in other languages. Used with a +C loop or the experimental C block, C can be used in +Perl to implement C/C like statements. Available as a +statement after Perl 5.10 and as a statement modifier after 5.14. +Here are three examples: + + use v5.10; + foreach (@fruits) { + when (/apples?/) { + say "I like apples." + } + when (/oranges?/) { + say "I don't like oranges." + } + default { + say "I don't like anything" + } + } + + # require 5.14 for when as statement modifier + use v5.14; + foreach (@fruits) { + say "I like apples." when /apples?/; + say "I don't like oranges." when /oranges?; + default { say "I don't like anything" } + } + + use v5.10; + given ($fruit) { + when (/apples?/) { + say "I like apples." + } + when (/oranges?/) { + say "I don't like oranges." + } + default { + say "I don't like anything" + } + } + +See L for detailed information. + =item write FILEHANDLE X @@ -7779,15 +8184,15 @@ a file is the one having the same name as the filehandle, but the format for the current output channel (see the C