X-Git-Url: https://perl5.git.perl.org/perl5.git/blobdiff_plain/4c050ad563ece4467b3b083d8efcf2b62ad0b9c5..1dfd34184395e3ce614d932eb8122349aa4a660c:/pod/perlfunc.pod diff --git a/pod/perlfunc.pod b/pod/perlfunc.pod index ccffcdb..62f9c6d 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. @@ -125,7 +125,7 @@ C, C, C =item Functions for real @ARRAYs X -C, C, C, C, C +C, C, C, C, C, C, C, C =item Functions for list data X @@ -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. @@ -1920,25 +2039,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 @@ -1947,11 +2062,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 @@ -1972,7 +2087,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. @@ -2004,6 +2119,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 @@ -2033,6 +2150,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 @@ -2071,6 +2196,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 @@ -2105,7 +2234,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 @@ -2120,10 +2249,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); @@ -2137,10 +2269,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 @@ -2153,13 +2287,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 @@ -2246,7 +2384,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. @@ -2270,7 +2408,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, @@ -2279,10 +2417,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 @@ -2312,9 +2450,16 @@ you can write this: $ip_address = inet_ntoa($packed_ip); } -Make sure is called in SCALAR context and that +Make sure C is called in SCALAR context and that its return value is checked for definedness. +The C function, even though it only takes one argument, +has the precedence of a list operator, so beware: + + getprotobynumber $number eq 'icmp' # WRONG + getprotobynumber($number eq 'icmp') # actually means this + getprotobynumber($number) eq 'icmp' # better this way + If you get tired of remembering which element of the return list contains which return value, by-name interfaces are provided in standard modules: C, C, C, @@ -2327,10 +2472,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 @@ -2359,12 +2506,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); @@ -2376,6 +2523,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 @@ -2393,7 +2565,20 @@ more detail in L. Note that C splits its arguments on whitespace and treats each segment as separate pattern. As such, C matches all files with a F<.c> or F<.h> extension. The expression -C matchs all files in the current working directory. +C matches all files in the current working directory. +If you want to glob filenames that might contain whitespace, you'll +have to use extra quotes around the spacey filename to protect it. +For example, to glob filenames that have an C followed by a space +followed by an C, use either of: + + @spacies = <"*e f*">; + @spacies = glob '"*e f*"'; + @spacies = glob q("*e f*"); + +If you had to get a variable through, you could do this: + + @spacies = glob "'*${var}e f*'"; + @spacies = glob qq("*${var}e f*"); If non-empty braces are the only wildcard characters used in the C, no filenames are matched, but potentially many strings @@ -2406,19 +2591,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 @@ -2443,6 +2630,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 @@ -2462,7 +2653,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 @@ -2515,7 +2706,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 @@ -2536,9 +2727,8 @@ It returns the position of the first occurrence of SUBSTR in STR at or after POSITION. If POSITION is omitted, starts searching from the beginning of the string. POSITION before the beginning of the string or after its end is treated as if it were the beginning or the end, -respectively. POSITION and the return value are based at C<0> (or whatever -you've set the C<$[> variable to--but don't do that). If the substring -is not found, C returns one less than the base, ordinarily C<-1>. +respectively. POSITION and the return value are based at zero. +If the substring is not found, C returns -1. =item int EXPR X X X X X @@ -2591,6 +2781,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 @@ -2607,6 +2799,8 @@ X X =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.) @@ -2614,11 +2808,11 @@ The keys of a hash are returned in an apparently random order. The actual random order is subject to change in future versions of Perl, but it is guaranteed to be the same order as either the C or C function produces (given that the hash has not been modified). Since -Perl 5.8.1 the ordering is different even between different runs of +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. @@ -2662,9 +2856,19 @@ 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. -See also C, C and C. +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) { ... } + +See also C, C, and C. =item kill SIGNAL, LIST + +=item kill SIGNAL X X Sends a signal to a list of processes. Returns the number of @@ -2691,6 +2895,20 @@ 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. + +If there is no I of processes, no signal is sent, and the return +value is 0. This form is sometimes used, however, because it causes +tainting checks to be run. But see +L. + +Portability issues: L. + =item last LABEL X X @@ -2707,7 +2925,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 @@ -2746,20 +2964,29 @@ respectively. =back -=item Otherwise, If EXPR has the UTF8 flag set +=item Otherwise, if C is in effect -If the current package has a subroutine named C, it will be used to -change the case (See L.) -Otherwise Unicode semantics are used for the case change. +Respects current LC_CTYPE locale for code points < 256; and uses Unicode +semantics for the remaining code points (this last can only happen if +the UTF8 flag is also set). See L. -=item Otherwise, if C is in effect +A deficiency in this is that case changes that cross the 255/256 +boundary are not well-defined. For example, the lower case of LATIN CAPITAL +LETTER SHARP S (U+1E9E) in Unicode semantics is U+00DF (on ASCII +platforms). But under C, the lower case of U+1E9E is +itself, because 0xDF may not be LATIN SMALL LETTER SHARP S in the +current locale, and Perl has no way of knowing if that character even +exists in the locale, much less what code point it is. Perl returns +the input character unchanged, for all instances (and there aren't +many) where the 255/256 boundary would otherwise be crossed. + +=item Otherwise, If EXPR has the UTF8 flag set -Respects current LC_CTYPE locale. See L. +Unicode semantics are used for the case change. =item Otherwise, if C is in effect: -Unicode semantics are used for the case change. Any subroutine named -C will not be used. +Unicode semantics are used for the case change. =item Otherwise: @@ -2789,7 +3016,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 @@ -2798,7 +3025,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 (you'll have to C first). See L and L. +=item __LINE__ +X<__LINE__> + +A special token that compiles to the current line number. + =item link OLDFILE,NEWFILE X Creates a new filename linked to the old filename. Returns true for success, false otherwise. +Portability issues: L. + =item listen SOCKET,QUEUESIZE X @@ -2851,19 +3086,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: @@ -2872,7 +3107,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); @@ -2890,13 +3125,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: @@ -2908,21 +3143,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, array or subroutine. + 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. @@ -2934,7 +3172,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: @@ -2945,9 +3184,13 @@ divided by the natural log of N. For example: See also L for the inverse operation. -=item lstat EXPR +=item lstat FILEHANDLE X +=item lstat EXPR + +=item lstat DIRHANDLE + =item lstat Does the same thing as the C function (including setting the @@ -2958,6 +3201,8 @@ information, please see the documentation for C. If EXPR is omitted, stats C<$_>. +Portability issues: L. + =item m// The match operator. See L. @@ -2974,9 +3219,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; @@ -3031,12 +3294,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 @@ -3061,14 +3324,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 @@ -3078,21 +3347,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 @@ -3107,7 +3380,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, @@ -3131,7 +3404,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 @@ -3199,67 +3472,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 can't 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 @@ -3268,21 +3540,24 @@ 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. +Those layers will also be ignored if you specifying a colon with no name +following it. In that case the default layer for the operating system +(:raw on Unix, :crlf on Windows) is used. Open returns nonzero on success, the undefined value otherwise. If the C involved a pipe, the return value happens to be the pid of @@ -3303,43 +3578,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; } @@ -3380,24 +3656,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 @@ -3405,8 +3681,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"; @@ -3435,26 +3711,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 @@ -3463,22 +3760,29 @@ piped open when you want to exercise more control over just how the pipe command gets executed, such as when running setuid and you don't want to have to scan shell commands for metacharacters. -The following triples are more or less equivalent: +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 example 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. @@ -3490,14 +3794,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: @@ -3505,33 +3809,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) @@ -3543,24 +3850,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 @@ -3569,19 +3888,19 @@ 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 =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 omitted, -uses C<$_>. +Returns the numeric 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. @@ -3599,14 +3918,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. @@ -3676,7 +3995,8 @@ of values, as follows: A A text (ASCII) string, will be space padded. Z A null-terminated (ASCIZ) string, will be null padded. - b A bit string (ascending bit order inside each byte, like vec()). + b A bit string (ascending bit order inside each byte, + like vec()). B A bit string (descending bit order inside each byte). h A hex string (low nybble first). H A hex string (high nybble first). @@ -3693,49 +4013,52 @@ of values, as follows: q A signed quad (64-bit) value. Q An unsigned quad value. - (Quads are available only if your system supports 64-bit - integer values _and_ if Perl has been compiled to support those. - Raises an exception otherwise.) + (Quads are available only if your system supports 64-bit + integer values _and_ if Perl has been compiled to support + those. Raises an exception otherwise.) i A signed integer value. I A unsigned integer value. - (This 'integer' is _at_least_ 32 bits wide. Its exact - size depends on what a local C compiler calls 'int'.) + (This 'integer' is _at_least_ 32 bits wide. Its exact + size depends on what a local C compiler calls 'int'.) n An unsigned short (16-bit) in "network" (big-endian) order. N An unsigned long (32-bit) in "network" (big-endian) order. v An unsigned short (16-bit) in "VAX" (little-endian) order. V An unsigned long (32-bit) in "VAX" (little-endian) order. - j A Perl internal signed integer value (IV). - J A Perl internal unsigned integer value (UV). + j A Perl internal signed integer value (IV). + J A Perl internal unsigned integer value (UV). f A single-precision float in native format. d A double-precision float in native format. F A Perl internal floating-point value (NV) in native format D A float of long-double precision in native format. - (Long doubles are available only if your system supports long - double values _and_ if Perl has been compiled to support those. - Raises an exception otherwise.) + (Long doubles are available only if your system supports + long double values _and_ if Perl has been compiled to + support those. Raises an exception otherwise.) p A pointer to a null-terminated string. P A pointer to a structure (fixed-length string). u A uuencoded string. - U A Unicode character number. Encodes to a character in character mode - and UTF-8 (or UTF-EBCDIC in EBCDIC platforms) in byte mode. + U A Unicode character number. Encodes to a character in char- + acter mode and UTF-8 (or UTF-EBCDIC in EBCDIC platforms) in + byte mode. - w A BER compressed integer (not an ASN.1 BER, see perlpacktut for - details). Its bytes represent an unsigned integer in base 128, - most significant digit first, with as few digits as possible. Bit - eight (the high bit) is set on each byte except the last. + w A BER compressed integer (not an ASN.1 BER, see perlpacktut + for details). Its bytes represent an unsigned integer in + base 128, most significant digit first, with as few digits + as possible. Bit eight (the high bit) is set on each byte + except the last. x A null byte (a.k.a ASCII NUL, "\000", chr(0)) X Back up a byte. @ Null-fill or truncate to absolute position, counted from the start of the innermost ()-group. - . Null-fill or truncate to absolute position specified by the value. + . Null-fill or truncate to absolute position specified by + the value. ( Start of a ()-group. One or more modifiers below may optionally follow certain letters in the @@ -3773,7 +4096,7 @@ count. A numeric repeat count may optionally be enclosed in brackets, as in C. The repeat count gobbles that many values from the LIST when used with all format types other than C, C, C, C, C, C, C, C<@>, C<.>, C, C, and 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 @@ -4118,6 +4444,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, @@ -4173,7 +4519,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. @@ -4188,12 +4534,14 @@ Examples: $foo = pack("W4",0x24b6,0x24b7,0x24b8,0x24b9); # same thing with Unicode circled letters. $foo = pack("U4",0x24b6,0x24b7,0x24b8,0x24b9); - # same thing with Unicode circled letters. You don't get the UTF-8 - # bytes because the U at the start of the format caused a switch to - # U0-mode, so the UTF-8 bytes get joined into characters + # same thing with Unicode circled letters. You don't get the + # UTF-8 bytes because the U at the start of the format caused + # a switch to U0-mode, so the UTF-8 bytes get joined into + # characters $foo = pack("C0U4",0x24b6,0x24b7,0x24b8,0x24b9); # foo eq "\xe2\x92\xb6\xe2\x92\xb7\xe2\x92\xb8\xe2\x92\xb9" - # This is the UTF-8 encoding of the string in the previous example + # This is the UTF-8 encoding of the string in the + # previous example $foo = pack("ccxxcc",65,66,67,68); # foo eq "AB\0\0CD" @@ -4204,8 +4552,8 @@ Examples: # $foo = pack("WWWW",193,194,195,196); $foo = pack("s2",1,2); - # "\1\0\2\0" on little-endian - # "\0\1\0\2" on big-endian + # "\001\000\002\000" on little-endian + # "\000\001\000\002" on big-endian $foo = pack("a4","abcd","x","y","z"); # "abcd" @@ -4249,27 +4597,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 @@ -4299,16 +4650,24 @@ 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 __PACKAGE__ +X<__PACKAGE__> + +A special token that returns the name of the package in which it occurs. + =item pop ARRAY X X +=item pop EXPR + =item pop Pops and returns the last value of the array, shortening the array by @@ -4318,53 +4677,71 @@ 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. +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 =item pos -Returns the offset of where the last C search left off for the variable -in question (C<$_> is used when the variable is not specified). Note that -0 is a valid match offset. C indicates that the search position -is reset (usually due to match failure, but can also be because no match has -yet been run on the scalar). C directly accesses the location used -by the regexp engine to store the offset, so assigning to C will change -that offset, and so will also influence the C<\G> zero-width assertion in -regular expressions. Because a failed C match doesn't reset the offset, -the return from C won't change either in this case. See L and +Returns the offset of where the last C search left off for the +variable in question (C<$_> is used when the variable is not +specified). Note that 0 is a valid match offset. C indicates +that the search position is reset (usually due to match failure, but +can also be because no match has yet been run on the scalar). + +C directly accesses the location used by the regexp engine to +store the offset, so assigning to C will change that offset, and +so will also influence the C<\G> zero-width assertion in regular +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. =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"; @@ -4375,15 +4752,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 @@ -4406,9 +4790,11 @@ describing the equivalent prototype is returned. =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; @@ -4417,6 +4803,11 @@ LIST. Has the same effect as but is more efficient. Returns the number of elements in the array following the completed C. +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/ =item qq/STRING/ @@ -4468,8 +4859,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 @@ -4494,6 +4890,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, L, +and L. + =item read FILEHANDLE,SCALAR,LENGTH,OFFSET X X @@ -4514,13 +4917,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. @@ -4555,7 +4959,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" @@ -4608,6 +5012,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 @@ -4639,7 +5045,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. @@ -4672,7 +5078,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 @@ -4741,6 +5147,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 @@ -4841,9 +5249,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 @@ -4862,8 +5270,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. @@ -4878,8 +5286,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 @@ -4957,7 +5365,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. @@ -5001,6 +5409,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 @@ -5016,7 +5426,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 @@ -5029,16 +5439,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 @@ -5054,10 +5469,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: @@ -5076,11 +5491,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 @@ -5132,11 +5547,12 @@ X @@ -5161,22 +5579,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: @@ -5203,19 +5621,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 @@ -5232,14 +5654,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 @@ -5248,7 +5674,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); @@ -5258,6 +5684,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 @@ -5288,6 +5716,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 @@ -5295,11 +5725,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). @@ -5309,9 +5741,13 @@ An example disabling Nagle's algorithm on a socket: use Socket qw(IPPROTO_TCP TCP_NODELAY); setsockopt($socket, IPPROTO_TCP, TCP_NODELAY, 1); +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 @@ -5320,7 +5756,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. + +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 @@ -5335,17 +5776,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 @@ -5357,9 +5802,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 @@ -5465,6 +5912,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 @@ -5485,13 +5934,16 @@ 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. + +If the subroutine is an XSUB, the elements to be compared are pushed on to +the stack, the way arguments are usually passed to XSUBs. $a and $b are +not set. The values to be compared are always passed by reference and should not be modified. @@ -5509,7 +5961,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 @@ -5548,7 +6000,7 @@ Examples: # sort using explicit subroutine name sub byage { - $age{$a} <=> $age{$b}; # presuming numeric + $age{$a} <=> $age{$b}; # presuming numeric } @sortedclass = sort byage @class; @@ -5568,8 +6020,8 @@ Examples: my @new = sort { ($b =~ /=(\d+)/)[0] <=> ($a =~ /=(\d+)/)[0] - || - uc($a) cmp uc($b) + || + uc($a) cmp uc($b) } @old; # same thing, but much more efficiently; @@ -5582,18 +6034,18 @@ Examples: } my @new = @old[ sort { - $nums[$b] <=> $nums[$a] - || - $caps[$a] cmp $caps[$b] - } 0..$#old - ]; + $nums[$b] <=> $nums[$a] + || + $caps[$a] cmp $caps[$b] + } 0..$#old + ]; # same thing, but without any temps @new = map { $_->[0] } sort { $b->[1] <=> $a->[1] - || - $a->[2] cmp $b->[2] - } map { [$_, /=(\d+)/, uc($_)] } @old; + || + $a->[2] cmp $b->[2] + } map { [$_, /=(\d+)/, uc($_)] } @old; # using a prototype allows you to use any comparison subroutine # as a sort subroutine (including other package's subroutines) @@ -5645,22 +6097,21 @@ 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), 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,OFFSET,LENGTH,LIST +=item splice ARRAY or EXPR,OFFSET,LENGTH,LIST X -=item splice ARRAY,OFFSET,LENGTH +=item splice ARRAY or EXPR,OFFSET,LENGTH -=item splice ARRAY,OFFSET +=item splice ARRAY or EXPR,OFFSET -=item splice ARRAY +=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, @@ -5675,7 +6126,7 @@ 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. -The following equivalences hold (assuming C<< $[ == 0 and $#a >= $i >> ) +The following equivalences hold (assuming C<< $#a >= $i >> ) push(@a,$x,$y) splice(@a,@a,0,$x,$y) pop(@a) splice(@a,-1) @@ -5696,6 +6147,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 @@ -5728,7 +6184,7 @@ specified. A pattern matching the empty string (not to be confused with an empty pattern C, which is just one member of the set of patterns -matching the epmty string), splits EXPR into individual +matching the empty string), splits EXPR into individual characters. For example: print join(':', split(/ */, 'hi there')), "\n"; @@ -5822,7 +6278,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: @@ -5867,7 +6323,7 @@ In addition, Perl permits the following widely-supported conversions: %B like %b, but using an upper-case "B" with the # flag %p a pointer (outputs the Perl value's address in hexadecimal) %n special: *stores* the number of characters output so far - into the next variable in the parameter list + into the next argument in the parameter list Finally, for backward (and we do mean "backward") compatibility, Perl permits these unnecessary but widely-supported conversions: @@ -5966,11 +6422,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. @@ -5980,7 +6436,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: @@ -5992,7 +6448,7 @@ For example: printf '<%.1e>', 10; # prints "<1.0e+01>" For "g" and "G", this specifies the maximum number of digits to show, -including thoe prior to the decimal point and those after it; for +including those prior to the decimal point and those after it; for example: # These examples are subject to system-specific variation. @@ -6060,15 +6516,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 + +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"; -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: +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) { @@ -6157,32 +6628,31 @@ X X X =item srand -Sets the random number seed for the C operator. +Sets and returns the random number seed for the C operator. The point of the function is to "seed" the C function so that C can produce a different sequence each time you run your -program. - -If srand() is not called explicitly, it is called implicitly at the -first use of the C operator. However, this was not true of -versions of Perl before 5.004, so if your script will run under older -Perl versions, it should call C. - -Most programs won't even call srand() at all, except those that -need a cryptographically-strong starting point rather than the -generally acceptable default, which is based on time of day, -process ID, and memory allocation, or the F device -if available. - -You can call srand($seed) with the same $seed to reproduce the -I sequence from rand(), but this is usually reserved for -generating predictable results for testing or debugging. -Otherwise, don't call srand() more than once in your program. - -Do B call srand() (i.e., without an argument) more than once in -a script. The internal state of the random number generator should +program. When called with a parameter, C uses that for the seed; +otherwise it (semi-)randomly chooses a seed. In either case, starting with +Perl 5.14, it returns the seed. + +If C is not called explicitly, it is called implicitly without a +parameter at the first use of the C operator. However, this was not true +of versions of Perl before 5.004, so if your script will run under older +Perl versions, it should call C; otherwise most programs won't call +C at all. + +But there are a few situations in recent Perls where programs are likely to +want to call C. One is for generating predictable results generally for +testing or debugging. There, you use C, with the same C<$seed> +each time. Another case is that you may want to call C +after a C to avoid child processes sharing the same seed value as the +parent (and consequently each other). + +Do B call C (i.e., without an argument) more than once per +process. The internal state of the random number generator should contain more entropy than can be provided by any seed, so calling -srand() again actually I randomness. +C again actually I randomness. Most implementations of C take an integer and will silently truncate decimal numbers. This means C will usually @@ -6194,16 +6664,6 @@ current C

, where it means -something else, dscribed below. Supplying a C<*> for the repeat count +something else, described below. Supplying a C<*> for the repeat count instead of a number means to use however many items are left, except for: =over @@ -3826,7 +4149,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 @@ -3840,17 +4163,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"> @@ -3869,21 +4193,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<"\0"> and C<"\1">. For characters C<"a".."f"> and C<"A".."F">, the result +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 @@ -3943,12 +4267,14 @@ the I is the string length, not the number of strings. With an explicit repeat count for pack, the packed string is adjusted to that length. For example: - unpack("W/a", "\04Gurusamy") gives ("Guru") - unpack("a3/A A*", "007 Bond J ") gives (" Bond", "J") - unpack("a3 x2 /A A*", "007: Bond, J.") gives ("Bond, J", ".") + This code: gives this result: + + unpack("W/a", "\004Gurusamy") ("Guru") + unpack("a3/A A*", "007 Bond J ") (" Bond", "J") + unpack("a3 x2 /A A*", "007: Bond, J.") ("Bond, J", ".") - pack("n/a* w/a","hello,","world") gives "\000\006hello,\005world" - pack("a/W2", ord("a") .. ord("z")) gives "2ab" + pack("n/a* w/a","hello,","world") "\000\006hello,\005world" + pack("a/W2", ord("a") .. ord("z")) "2ab" The I is not returned explicitly from C. @@ -4010,8 +4336,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 @@ -4051,10 +4377,10 @@ Starting with Perl 5.9.2, integer and floating-point formats, along with the C