X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=blobdiff_plain;f=pod%2Fperlfunc.pod;h=b918cac80c86293d26e6a28469bcc77313458217;hb=938c8732ceb115a707f725327a631eb35319ba87;hp=3d5947958f3a25045aa6ebb8d48a2bb54ba917da;hpb=6d822dc4045278fb03135b2683bac92dba061369;p=p5sagit%2Fp5-mst-13.2.git diff --git a/pod/perlfunc.pod b/pod/perlfunc.pod index 3d59479..b918cac 100644 --- a/pod/perlfunc.pod +++ b/pod/perlfunc.pod @@ -224,8 +224,8 @@ by this are: C<-X>, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, -C, C, C, C, C, C, -C, C, C, C, +C, C, C, C, C, C, +C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, @@ -246,11 +246,11 @@ L and other available platform-specific documentation. =over 8 -=item I<-X> FILEHANDLE +=item -X FILEHANDLE -=item I<-X> EXPR +=item -X EXPR -=item I<-X> +=item -X A file test, where X is one of the letters listed below. This unary operator takes one argument, either a filename or a filehandle, and @@ -366,6 +366,12 @@ Example: print "Text\n" if -T _; print "Binary\n" if -B _; +As of Perl 5.9.1, as a form of purely syntactic sugar, you can stack file +test operators, in a way that C<-f -w -x $file> is equivalent to +C<-x $file && -w _ && -f _>. (This is only syntax fancy : if you use +the return value of C<-f $file> as an argument to another filetest +operator, no special magic will happen.) + =item abs VALUE =item abs @@ -429,6 +435,8 @@ modulo the caveats given in L. # didn't } +For more information see L. + =item atan2 Y,X Returns the arctangent of Y/X in the range -PI to PI. @@ -453,17 +461,34 @@ Arranges for FILEHANDLE to be read or written in "binary" or "text" mode on systems where the run-time libraries distinguish between binary and text files. If FILEHANDLE is an expression, the value is taken as the name of the filehandle. Returns true on success, -C on failure. +otherwise it returns C and sets C<$!> (errno). + +On some systems (in general, DOS and Windows-based systems) binmode() +is necessary when you're not working with a text file. For the sake +of portability it is a good idea to always use it when appropriate, +and to never use it when it isn't appropriate. Also, people can +set their I/O to be by default UTF-8 encoded Unicode, not bytes. + +In other words: regardless of platform, use binmode() on binary data, +like for example images. + +If LAYER is present it is a single string, but may contain multiple +directives. The directives alter the behaviour of the file handle. +When LAYER is present using binmode on text file makes sense. If LAYER is omitted or specified as C<:raw> the filehandle is made suitable for passing binary data. This includes turning off possible CRLF translation and marking it as bytes (as opposed to Unicode characters). -Note that as desipite what may be implied in I<"Programming Perl"> -(the Camel) or elsewhere C<:raw> is I the simply inverse of C<:crlf> +Note that, despite what may be implied in I<"Programming Perl"> (the +Camel) or elsewhere, C<:raw> is I the simply inverse of C<:crlf> -- other layers which would affect binary nature of the stream are I disabled. See L, L and the discussion about the PERLIO environment variable. +The C<:bytes>, C<:crlf>, and C<:utf8>, and any other directives of the +form C<:...>, are called I/O I. The C pragma can be used to +establish default I/O layers. See L. + I -On some systems (in general, DOS and Windows-based systems) binmode() -is necessary when you're not working with a text file. For the sake -of portability it is a good idea to always use it when appropriate, -and to never use it when it isn't appropriate. - -In other words: regardless of platform, use binmode() on binary files -(like for example images). - -If LAYER is present it is a single string, but may contain -multiple directives. The directives alter the behaviour of the -file handle. When LAYER is present using binmode on text -file makes sense. - To mark FILEHANDLE as UTF-8, use C<:utf8>. -The C<:bytes>, C<:crlf>, and C<:utf8>, and any other directives of the -form C<:...>, are called I/O I. The C pragma can be used to -establish default I/O layers. See L. - In general, binmode() should be called after open() but before any I/O is done on the filehandle. Calling binmode() will normally flush any pending buffered output data (and perhaps pending input data) on the handle. An exception to this is the C<:encoding> layer that changes the default character encoding of the handle, see L. The C<:encoding> layer sometimes needs to be called in -mid-stream, and it doesn't flush the stream. +mid-stream, and it doesn't flush the stream. The C<:encoding> +also implicitly pushes on top of itself the C<:utf8> layer because +internally Perl will operate on UTF-8 encoded Unicode characters. The operating system, device drivers, C libraries, and Perl run-time system all work together to let the programmer treat a single @@ -657,6 +667,10 @@ You can actually chomp anything that's an lvalue, including an assignment: If you chomp a list, each element is chomped, and the total number of characters removed is returned. +If the C pragma is in scope then the lengths returned are +calculated from the length of C<$/> in Unicode characters, which is not +always the same as the length of C<$/> in the native encoding. + Note that parentheses are necessary when you're chomping anything that is not a simple variable. This is because C is interpreted as C<(chomp $cwd) = `pwd`;>, rather than as @@ -724,14 +738,18 @@ On POSIX systems, you can detect this condition this way: Returns the character represented by that NUMBER in the character set. For example, C is C<"A"> in either ASCII or Unicode, and -chr(0x263a) is a Unicode smiley face. Note that characters from 127 -to 255 (inclusive) are by default not encoded in Unicode for backward -compatibility reasons (but see L). +chr(0x263a) is a Unicode smiley face. Note that characters from 128 +to 255 (inclusive) are by default not encoded in UTF-8 Unicode for +backward compatibility reasons (but see L). + +If NUMBER is omitted, uses C<$_>. For the reverse, use L. -See L and L for more about Unicode. -If NUMBER is omitted, uses C<$_>. +Note that under the C pragma the NUMBER is masked to +the low eight bits. + +See L and L for more about Unicode. =item chroot FILENAME @@ -758,10 +776,10 @@ another C on it, because C will close it for you. (See C.) However, an explicit C on an input file resets the line counter (C<$.>), while the implicit close done by C does not. -If the file handle came from a piped open C will additionally -return false if one of the other system calls involved fails or if the +If the file handle came from a piped open, C will additionally +return false if one of the other system calls involved fails, or if the program exits with non-zero status. (If the only problem was that the -program exited non-zero C<$!> will be set to C<0>.) Closing a pipe +program exited non-zero, C<$!> will be set to C<0>.) Closing a pipe also waits for the process executing on the pipe to complete, in case you want to look at the output of the pipe afterwards, and implicitly puts the exit status value of that command into C<$?>. @@ -790,9 +808,6 @@ filehandle, usually the real filehandle name. Closes a directory opened by C and returns the success of that system call. -DIRHANDLE may be an expression whose value can be used as an indirect -dirhandle, usually the real dirhandle name. - =item connect SOCKET,NAME Attempts to connect to a remote socket, just as the connect system call @@ -849,7 +864,7 @@ extirpated as a potential munition). This can prove useful for checking the password file for lousy passwords, amongst other things. Only the guys wearing white hats should do this. -Note that C is intended to be a one-way function, much like +Note that L is intended to be a one-way function, much like breaking eggs to make an omelette. There is no (known) corresponding decrypt function (in other words, the crypt() is a one-way hash function). As a result, this function isn't all that useful for @@ -857,7 +872,7 @@ cryptography. (For that, see your nearby CPAN mirror.) When verifying an existing encrypted string you should use the encrypted text as the salt (like C). This allows your code to work with the standard C +$crypted>). This allows your code to work with the standard L and with more exotic implementations. In other words, do not assume anything about the returned string itself, or how many bytes in the encrypted string matter. @@ -871,7 +886,10 @@ different strings. When choosing a new salt create a random two character string whose characters come from the set C<[./0-9A-Za-z]> (like C). +'/', 0..9, 'A'..'Z', 'a'..'z')[rand 64, rand 64]>). This set of +characters is just a recommendation; the characters allowed in +the salt depend solely on your system's crypt library, and Perl can't +restrict what salts C accepts. Here's an example that makes sure that whoever runs this program knows their own password: @@ -893,7 +911,7 @@ their own password: Of course, typing in your own password to whoever asks you for it is unwise. -The L function is unsuitable for encrypting large quantities +The L function is unsuitable for encrypting large quantities of data, not least of all because you can't get the information back. Look at the F and F directories on your favorite CPAN mirror for a slew of potentially useful @@ -974,7 +992,7 @@ element to return happens to be C. You may also use C to check whether subroutine C<&func> has ever been defined. The return value is unaffected by any forward -declarations of C<&foo>. Note that a subroutine which is not defined +declarations of C<&func>. Note that a subroutine which is not defined may still be callable: its package may have an C method that makes it spring into existence the first time that it is called -- see L. @@ -1025,8 +1043,18 @@ In the case of an array, if the array elements happen to be at the end, the size of the array will shrink to the highest element that tests true for exists() (or 0 if no such element exists). -Returns each element so deleted or the undefined value if there was no such -element. Deleting from C<$ENV{}> modifies the environment. Deleting from +Returns a list with the same number of elements as the number of elements +for which deletion was attempted. Each element of that list consists of +either the value of the element deleted, or the undefined value. In scalar +context, this means that you get the value of the last element deleted (or +the undefined value if that element did not exist). + + %hash = (foo => 11, bar => 22, baz => 33); + $scalar = delete $hash{foo}; # $scalar is 11 + $scalar = delete @hash{qw(foo bar)}; # $scalar is 22 + @array = delete @hash{qw(foo bar baz)}; # @array is (undef,undef,33) + +Deleting from C<%ENV> modifies the environment. Deleting from a hash tied to a DBM file deletes the entry from the DBM file. Deleting from a Cd hash or array may not necessarily return anything. @@ -1117,7 +1145,7 @@ This is useful for propagating exceptions: If LIST is empty and C<$@> contains an object reference that has a C method, that method will be called with additional file and line number parameters. The return value replaces the value in -C<$@>. ie. as if C<<$@ = eval { $@->PROPAGATE(__FILE__, __LINE__) };>> +C<$@>. ie. as if C<< $@ = eval { $@->PROPAGATE(__FILE__, __LINE__) }; >> were called. If C<$@> is empty then the string C<"Died"> is used. @@ -1259,9 +1287,11 @@ it. When called in scalar context, returns only the key for the next element in the hash. Entries 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 in the same order as either the C or C function -would produce on the same (unmodified) hash. +order is subject to change in future versions of perl, but it is +guaranteed to be in the same order as either the C or C +function would produce on the same (unmodified) hash. Since Perl +5.8.1 the ordering is different even between different runs of Perl +for security reasons (see L). When the hash is entirely read, a null array is returned in list context (which when assigned produces a false (C<0>) value), and C in @@ -1327,12 +1357,11 @@ last file. Examples: # insert dashes just before last line of last file while (<>) { - if (eof()) { # check for end of current file + if (eof()) { # check for end of last file print "--------------\n"; - close(ARGV); # close or last; is needed if we - # are reading from the terminal } print; + last if eof(); # needed if we're reading from a terminal } Practical hint: you almost never need to use C in Perl, because the @@ -1449,6 +1478,11 @@ in case 6. C does I count as a loop, so the loop control statements C, C, or C cannot be used to leave or restart the block. +Note that as a very special case, an C executed within the C +package doesn't see the usual surrounding lexical scope, but rather the +scope of the first non-DB piece of code that called it. You don't normally +need to worry about this unless you are writing a Perl debugger. + =item exec LIST =item exec PROGRAM LIST @@ -1630,7 +1664,7 @@ For example: fcntl($filehandle, F_GETFL, $packed_return_buffer) or die "can't fcntl F_GETFL: $!"; -You don't have to check for C on the return from C. +You don't have to check for C on the return from C. Like C, it maps a C<0> return from the system call into C<"0 but true"> in Perl. This string is true in boolean context and C<0> in numeric context. It is also exempt from the normal B<-w> warnings @@ -1640,6 +1674,18 @@ Note that C will produce a fatal error if used on a machine that doesn't implement fcntl(2). See the Fcntl module or your fcntl(2) manpage to learn what functions are available on your system. +Here's an example of setting a filehandle named C to be +non-blocking at the system level. You'll have to negotiate C<$|> +on your own, though. + + use Fcntl qw(F_GETFL F_SETFL O_NONBLOCK); + + $flags = fcntl(REMOTE, F_GETFL, 0) + or die "Can't get flags for the socket: $!\n"; + + $flags = fcntl(REMOTE, F_SETFL, $flags | O_NONBLOCK) + or die "Can't set flags for the socket: $!\n"; + =item fileno FILEHANDLE Returns the file descriptor for a filehandle, or undefined if the @@ -1805,11 +1851,11 @@ C always returns true. See L for other examples. =item getc Returns the next character from the input file attached to FILEHANDLE, -or the undefined value at end of file, or if there was an error. -If FILEHANDLE is omitted, reads from STDIN. This is not particularly -efficient. However, it cannot be used by itself to fetch single -characters without waiting for the user to hit enter. For that, try -something more like: +or the undefined value at end of file, or if there was an error (in +the latter case C<$!> is set). If FILEHANDLE is omitted, reads from +STDIN. This is not particularly efficient. However, it cannot be +used by itself to fetch single characters without waiting for the user +to hit enter. For that, try something more like: if ($BSD_STYLE) { system "stty cbreak /dev/tty 2>&1"; @@ -1870,6 +1916,13 @@ does not accept a PID argument, so only C is truly portable. Returns the process id of the parent process. +Note for Linux users: on Linux, the C functions C and +C return different values from different threads. In order to +be portable, this behavior is not reflected by the perl-level function +C, that returns a consistent value across threads. If you want +to call the underlying C, you may use the CPAN module +C. + =item getpriority WHICH,WHO Returns the current priority for a process, a process group, or a user. @@ -1966,7 +2019,7 @@ lookup by name, in which case you get the other thing, whatever it is. $name = getpwuid($num); $name = getpwent(); $gid = getgrnam($name); - $name = getgrgid($num; + $name = getgrgid($num); $name = getgrent(); #etc. @@ -2044,7 +2097,34 @@ IPs that the connection might have come in on. =item getsockopt SOCKET,LEVEL,OPTNAME -Returns the socket option requested, or undef if there is an error. +Queries the option named OPTNAME associated with SOCKET at a given LEVEL. +Options may exist at multiple protocol levels depending on the socket +type, but at least the uppermost socket level SOL_SOCKET (defined in the +C module) will exist. To query options at another level the +protocol number of the appropriate protocol controlling the option +should be supplied. For example, to indicate that an option is to be +interpreted by the TCP protocol, LEVEL should be set to the protocol +number of TCP, which you can get using getprotobyname. + +The call returns a packed string representing the requested socket option, +or C if there is an error (the error reason will be in $!). What +exactly is in the packed string depends in the LEVEL and OPTNAME, consult +your system documentation for details. A very common case however is that +the option is an integer, in which case the result will be an packed +integer which you can decode using unpack with the C (or C) format. + +An example testing if Nagle's algorithm is turned on on a socket: + + use Socket; + + defined(my $tcp = getprotobyname("tcp")) + or die "Could not determine the protocol number for tcp"; + # my $tcp = Socket::IPPROTO_TCP; # Alternative + my $packed = getsockopt($socket, $tcp, Socket::TCP_NODELAY) + or die "Could not query TCP_NODELAY SOCKEt option: $!"; + my $nodelay = unpack("I", $packed); + print "Nagle's algorithm is turned ", $nodelay ? "off\n" : "on\n"; + =item glob EXPR @@ -2098,22 +2178,13 @@ In scalar context, C returns the ctime(3) value: $now_string = gmtime; # e.g., "Thu Oct 13 04:54:34 1994" -Also see the C function provided by the C module, -and the strftime(3) function available via the POSIX module. +If you need local time instead of GMT use the L builtin. +See also the C function provided by the C module, +and the strftime(3) and mktime(3) functions available via the L module. -This scalar value is B locale dependent (see L), but -is instead a Perl builtin. Also see the C module, and the -strftime(3) and mktime(3) functions available via the POSIX module. To -get somewhat similar but locale dependent date strings, set up your -locale environment variables appropriately (please see L) -and try for example: - - use POSIX qw(strftime); - $now_string = strftime "%a %b %e %H:%M:%S %Y", gmtime; - -Note that the C<%a> and C<%b> escapes, which represent the short forms -of the day of the week and the month of the year, may not necessarily -be three characters wide in all locales. +This scalar value is B locale dependent (see L), but is +instead a Perl builtin. To get somewhat similar but locale dependent date +strings, see the example in L. =item goto LABEL @@ -2183,6 +2254,11 @@ element of a list returned by grep (for example, in a C, C or another C) actually modifies the element in the original list. This is usually something to be avoided when writing clear code. +If C<$_> is lexical in the scope where the C appears (because it has +been declared with C) then, in addition the be locally aliased to +the list elements, C<$_> keeps being lexical inside the block; i.e. it +can't be seen from the outside, avoiding any potential side-effects. + See also L for a list composed of the results of the BLOCK or EXPR. =item hex EXPR @@ -2265,21 +2341,9 @@ system: $retval = ioctl(...) || -1; printf "System returned %d\n", $retval; -The special string "C<0> but true" is exempt from B<-w> complaints +The special string C<"0 but true"> is exempt from B<-w> complaints about improper numeric conversions. -Here's an example of setting a filehandle named C to be -non-blocking at the system level. You'll have to negotiate C<$|> -on your own, though. - - use Fcntl qw(F_GETFL F_SETFL O_NONBLOCK); - - $flags = fcntl(REMOTE, F_GETFL, 0) - or die "Can't get flags for the socket: $!\n"; - - $flags = fcntl(REMOTE, F_SETFL, $flags | O_NONBLOCK) - or die "Can't set flags for the socket: $!\n"; - =item join EXPR,LIST Joins the separate strings of LIST into a single string with fields @@ -2292,13 +2356,20 @@ first argument. Compare L. =item keys HASH -Returns a list consisting of all the keys of the named hash. (In -scalar context, returns the number of keys.) The keys 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). As a side effect, it resets -HASH's iterator. +Returns a list consisting of all the keys of the named hash. +(In scalar context, returns the number of keys.) + +The keys 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 for security reasons (see L). + +As a side effect, calling keys() resets the HASH's internal iterator, +see L. (In particular, calling keys() in void context resets +the iterator with no other overhead.) Here is yet another way to print your environment: @@ -2351,7 +2422,7 @@ same as the number actually killed). kill 9, @goners; If SIGNAL is zero, no signal is sent to the process. This is a -useful way to check that the process is alive and hasn't changed +useful way to check that a child process is alive and hasn't changed its UID. See L for notes on the portability of this construct. @@ -2359,7 +2430,9 @@ Unlike in the shell, if SIGNAL is negative, it kills process groups instead of processes. (On System V, a negative I number will also kill process groups, but that's not portable.) That means you usually want to use positive not negative signals. You may also -use a signal name in quotes. See L for details. +use a signal name in quotes. + +See L for more details. =item last LABEL @@ -2413,11 +2486,15 @@ If EXPR is omitted, uses C<$_>. =item length -Returns the length in characters of the value of EXPR. If EXPR is +Returns the length in I of the value of EXPR. If EXPR is omitted, returns length of C<$_>. Note that this cannot be used on an entire array or hash to find out how many elements these have. For that, use C and C respectively. +Note the I: if the EXPR is in Unicode, you will get the +number of characters, not the number of bytes. To get the length +in bytes, use C, see L. + =item link OLDFILE,NEWFILE Creates a new filename linked to the old filename. Returns true for @@ -2479,17 +2556,20 @@ 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, see L, but -instead a Perl builtin. Also see the C module -(to convert the second, minutes, hours, ... back to seconds since the -stroke of midnight the 1st of January 1970, the value returned by -time()), and the strftime(3) and mktime(3) functions available via the -POSIX module. To get somewhat similar but locale dependent date -strings, set up your locale environment variables appropriately -(please see L) and try for example: +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 +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 +locale environment variables appropriately (please see L) and +try for example: use POSIX qw(strftime); $now_string = strftime "%a %b %e %H:%M:%S %Y", localtime; + # or for GMT formatted appropriately for your locale: + $now_string = strftime "%a %b %e %H:%M:%S %Y", gmtime; 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. @@ -2527,7 +2607,8 @@ See also L for the inverse operation. Does the same thing as the C function (including setting the special C<_> filehandle) but stats a symbolic link instead of the file the symbolic link points to. If symbolic links are unimplemented on -your system, a normal C is done. +your system, a normal C is done. For much more detailed +information, please see the documentation for C. If EXPR is omitted, stats C<$_>. @@ -2566,6 +2647,11 @@ Using a regular C loop for this purpose would be clearer in most cases. See also L for an array composed of those items of the original list for which the BLOCK or EXPR evaluates to true. +If C<$_> is lexical in the scope where the C appears (because it has +been declared with C) then, in addition the be locally aliased to +the list elements, C<$_> keeps being lexical inside the block; i.e. it +can't be seen from the outside, avoiding any potential side-effects. + C<{> starts both hash references and blocks, so C could be either the start of map BLOCK LIST or map EXPR, LIST. Because perl doesn't look ahead for the closing C<}> it has to take a guess at which its dealing with @@ -2702,7 +2788,7 @@ C work. =item no Module -See the L function, which C is the opposite of. +See the C function, of which C is the opposite. =item oct EXPR @@ -2744,11 +2830,11 @@ FILEHANDLE. (The following is a comprehensive reference to open(): for a gentler introduction you may consider L.) -If FILEHANDLE is an undefined lexical (C) variable 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 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 @@ -2844,9 +2930,14 @@ argument being C: open(TMP, "+>", undef) or die ... -opens a filehandle to an anonymous temporary file. +opens a filehandle to an anonymous temporary file. Also using "+<" +works for symmetry, but you really should consider writing something +to the temporary file first. You will need to seek() to do the +reading. -File handles can be opened to "in memory" files held in Perl scalars via: +Since v5.8.0, perl has built using PerlIO by default. Unless you've +changed this (ie Configure -Uuseperlio), you can open file handles to +"in memory" files held in Perl scalars via: open($fh, '>', \$variable) || .. @@ -2877,7 +2968,7 @@ Examples: open(ARTICLE, "caesar <$article |") # ditto or die "Can't start caesar: $!"; - open(EXTRACT, "|sort >/tmp/Tmp$$") # $$ is our process id + open(EXTRACT, "|sort >Tmp$$") # $$ is our process id or die "Can't start sort: $!"; # in memory files @@ -2909,15 +3000,17 @@ 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 as the -name of a filehandle (or file descriptor, if numeric) to be -duped 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". +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 L) 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". Here is a script that saves, redirects, and restores C and C using various methods: @@ -2935,29 +3028,46 @@ C using various methods: print STDOUT "stdout 1\n"; # this works for print STDERR "stderr 1\n"; # subprocesses too - close STDOUT; - close STDERR; - 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"; -If you specify C<< '<&=N' >>, where C is a number, then Perl will -do an equivalent of C's C of that file descriptor; this is -more parsimonious of file descriptors. For example: +If you specify C<< '<&=X' >>, where C is a file descriptor number +or a filehandle, then Perl will do an equivalent of C's C of +that file descriptor (and not call L); this is more +parsimonious of file descriptors. For example: + # open for input, reusing the fileno of $fd open(FILEHANDLE, "<&=$fd") or open(FILEHANDLE, "<&=", $fd) -Note that if Perl is using the standard C libraries' fdopen() then on -many UNIX systems, fdopen() is known to fail when file descriptors -exceed a certain value, typically 255. If you need more file -descriptors than that, consider rebuilding Perl to use the C. +or + + # open for append, using the fileno of OLDFH + open(FH, ">>&=", OLDFH) + +or + + open(FH, ">>&=OLDFH") + +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 @@ -3076,6 +3186,10 @@ See L for some details about mixing reading and writing. Opens a directory named EXPR for processing by C, C, 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. DIRHANDLEs have their own namespace separate from FILEHANDLEs. =item ord EXPR @@ -3164,6 +3278,11 @@ fork() emulation on Windows platforms, or by embedding perl in a multi-threaded application. The C attribute does nothing in all other environments. +Warning: the current implementation of this attribute operates on the +typeglob associated with the variable; this means that C +also has the effect of C. This may be +subject to change. + =item pack TEMPLATE,LIST Takes a LIST of values and converts it into a string using the rules @@ -3184,34 +3303,14 @@ of values, as follows: h A hex string (low nybble first). H A hex string (high nybble first). - c A signed char value. + c A signed char (8-bit) value. C An unsigned char value. Only does bytes. See U for Unicode. - s A signed short value. + s A signed short (16-bit) value. S An unsigned short value. - (This 'short' is _exactly_ 16 bits, which may differ from - what a local C compiler calls 'short'. If you want - native-length shorts, use the '!' suffix.) - - i A signed integer value. - I An unsigned integer value. - (This 'integer' is _at_least_ 32 bits wide. Its exact - size depends on what a local C compiler calls 'int', - and may even be larger than the 'long' described in - the next item.) - l A signed long value. + l A signed long (32-bit) value. L An unsigned long value. - (This 'long' is _exactly_ 32 bits, which may differ from - what a local C compiler calls 'long'. If you want - native-length longs, use the '!' suffix.) - - n An unsigned short in "network" (big-endian) order. - N An unsigned long in "network" (big-endian) order. - v An unsigned short in "VAX" (little-endian) order. - V An unsigned long in "VAX" (little-endian) order. - (These 'shorts' and 'longs' are _exactly_ 16 bits and - _exactly_ 32 bits, respectively.) q A signed quad (64-bit) value. Q An unsigned quad value. @@ -3219,14 +3318,23 @@ of values, as follows: integer values _and_ if Perl has been compiled to support those. Causes a fatal error otherwise.) - j A signed integer value (a Perl internal integer, IV). - J An unsigned integer value (a Perl internal unsigned integer, UV). + 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'.) + + 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). f A single-precision float in the native format. d A double-precision float in the native format. - F A floating point value in the native native format - (a Perl internal floating point value, NV). + F A Perl internal floating point value (NV) in the native format D A long double-precision float in the native format. (Long doubles are available only if your system supports long double values _and_ if Perl has been compiled to support those. @@ -3246,9 +3354,31 @@ of values, as follows: x A null byte. X Back up a byte. - @ Null fill to absolute position. + @ Null fill to absolute position, counted from the start of + the innermost ()-group. ( Start of a ()-group. +Some letters in the TEMPLATE may optionally be followed by one or +more of these modifiers (the second column lists the letters for +which the modifier is valid): + + ! sSlLiI Forces native (short, long, int) sizes instead + of fixed (16-/32-bit) sizes. + + xX Make x and X act as alignment commands. + + nNvV Treat integers as signed instead of unsigned. + + > sSiIlLqQ Force big-endian byte-order on the type. + jJfFdDpP (The "big end" touches the construct.) + + < sSiIlLqQ Force little-endian byte-order on the type. + jJfFdDpP (The "little end" touches the construct.) + +The C> and C> modifiers can also be used on C<()>-groups, +in which case they force a certain byte-order on all components of +that group, including subgroups. + The following rules apply: =over 8 @@ -3353,6 +3483,11 @@ The C

type packs a pointer to a structure of the size indicated by the length. A NULL pointer is created if the corresponding value for C

or C

is C, similarly for unpack(). +If your system has a strange pointer size (i.e. a pointer is neither as +big as an int nor as big as a long), it may not be possible to pack or +unpack pointers in big- or little-endian byte order. Attempting to do +so will result in a fatal error. + =item * The C template character allows packing and unpacking of strings where @@ -3364,9 +3499,11 @@ how the length value is packed. The ones likely to be of most use are integer-packing ones like C (for Java strings), C (for ASN.1 or SNMP) and C (for Sun XDR). -The I must, at present, be C<"A*">, C<"a*"> or C<"Z*">. -For C the length of the string is obtained from the I, -but if you put in the '*' it will be ignored. +For C, the I must, at present, be C<"A*">, C<"a*"> or +C<"Z*">. For C the length of the string is obtained from the +I, but if you put in the '*' it will be ignored. For all other +codes, C applies the length value to the next item, which must not +have a repeat count. unpack 'C/a', "\04Gurusamy"; gives 'Guru' unpack 'a3/A* A*', '007 Bond J '; gives (' Bond','J') @@ -3382,7 +3519,7 @@ which Perl does not regard as legal in numeric strings. =item * The integer types C, C, C, and C may be -immediately followed by a C suffix to signify native shorts or +followed by a C modifier to signify native shorts or longs--as you can see from above for example a bare C does mean exactly 32 bits, the native C (as seen by the local C compiler) may be larger. This is an issue mainly in 64-bit platforms. You can @@ -3404,7 +3541,7 @@ L: print $Config{longsize}, "\n"; print $Config{longlongsize}, "\n"; -(The C<$Config{longlongsize}> will be undefine if your system does +(The C<$Config{longlongsize}> will be undefined if your system does not support long longs.) =item * @@ -3448,12 +3585,45 @@ via L: Byteorders C<'1234'> and C<'12345678'> are little-endian, C<'4321'> and C<'87654321'> are big-endian. -If you want portable packed integers use the formats C, C, -C, and C, their byte endianness and size are known. +If you want portable packed integers you can either use the formats +C, C, C, and C, or you can use the C> and C> +modifiers. These modifiers are only available as of perl 5.8.5. See also L. =item * +All integer and floating point formats as well as C

and C

and +C<()>-groups may be followed by the C> or C> modifiers +to force big- or little- endian byte-order, respectively. +This is especially useful, since C, C, C and C don't cover +signed integers, 64-bit integers and floating point values. However, +there are some things to keep in mind. + +Exchanging signed integers between different platforms only works +if all platforms store them in the same format. Most platforms store +signed integers in two's complement, so usually this is not an issue. + +The C> or C> modifiers can only be used on floating point +formats on big- or little-endian machines. Otherwise, attempting to +do so will result in a fatal error. + +Forcing big- or little-endian byte-order on floating point values for +data exchange can only work if all platforms are using the same +binary representation (e.g. IEEE floating point format). Even if all +platforms are using IEEE, there may be subtle differences. Being able +to use C> or C> on floating point values can be very useful, +but also very dangerous if you don't know exactly what you're doing. +It is definetely not a general way to portably store floating point +values. + +When using C> or C> on an C<()>-group, this will affect +all types inside the group that accept the byte-order modifiers, +including all subgroups. It will silently be ignored for all other +types. You are not allowed to override the byte-order within a group +that already has a byte-order modifier suffix. + +=item * + Real numbers (floats and doubles) are in the native machine format only; due to the multiplicity of floating formats around, and the lack of a standard "network" representation, no facility for interchange has been @@ -3462,19 +3632,23 @@ may not be readable on another - even if both use IEEE floating point arithmetic (as the endian-ness of the memory representation is not part of the IEEE spec). See also L. -Note that Perl uses doubles internally for all numeric calculation, and -converting from double into float and thence back to double again will -lose precision (i.e., C) will not in general -equal $foo). +If you know exactly what you're doing, you can use the C> or C> +modifiers to force big- or little-endian byte-order on floating point values. + +Note that Perl uses doubles (or long doubles, if configured) internally for +all numeric calculation, and converting from double into float and thence back +to double again will lose precision (i.e., C) +will not in general equal $foo). =item * -If the pattern begins with a C, the resulting string will be treated -as Unicode-encoded. You can force UTF8 encoding on in a string with an -initial C, and the bytes that follow will be interpreted as Unicode -characters. If you don't want this to happen, you can begin your pattern -with C (or anything else) to force Perl not to UTF8 encode your -string, and then follow this with a C somewhere in your pattern. +If the pattern begins with a C, the resulting string will be +treated as UTF-8-encoded Unicode. You can force UTF-8 encoding on in a +string with an initial C, and the bytes that follow will be +interpreted as Unicode characters. If you don't want this to happen, +you can begin your pattern with C (or anything else) to force Perl +not to UTF-8 encode your string, and then follow this with a C +somewhere in your pattern. =item * @@ -3487,8 +3661,14 @@ sequences of bytes. =item * A ()-group is a sub-TEMPLATE enclosed in parentheses. A group may -take a repeat count, both as postfix, and via the C template -character. +take a repeat count, both as postfix, and for unpack() also via the C +template character. Within each repetition of a group, positioning with +C<@> starts again at 0. Therefore, the result of + + pack( '@1A((@2A)@3A)', 'a', 'b', 'c' ) + +is the string "\0a\0\0bc". + =item * @@ -3504,7 +3684,17 @@ both result in no-ops. =item * +C, C, C and C accept the C modifier. In this case they +will represent signed 16-/32-bit integers in big-/little-endian order. +This is only portable if all platforms sharing the packed data use the +same binary representation for signed integers (e.g. all platforms are +using two's complement representation). + +=item * + A comment in a TEMPLATE starts with C<#> and goes to the end of line. +White space may be used to separate pack codes from each other, but +modifiers and a repeat count must follow immediately. =item * @@ -3564,6 +3754,15 @@ Examples: # short 12, zero fill to position 4, long 34 # $foo eq $bar + $foo = pack('nN', 42, 4711); + # pack big-endian 16- and 32-bit unsigned integers + $foo = pack('S>L>', 42, 4711); + # exactly the same + $foo = pack('s of data into variable SCALAR from the specified FILEHANDLE. Returns the number of characters -actually read, C<0> at end of file, or undef if there was an error. -SCALAR will be grown or shrunk to the length actually read. If SCALAR -needs growing, the new bytes will be zero bytes. An OFFSET may be -specified to place the read data into some other place in SCALAR than -the beginning. The call is actually implemented in terms of either -Perl's or system's fread() call. To get a true read(2) system call, -see C. +actually read, C<0> at end of file, or undef if there was an error (in +the latter case C<$!> is also set). SCALAR will be grown or shrunk +so that the last character actually read is the last character of the +scalar after the read. + +An OFFSET may be specified to place the read data at some place in the +string other than the beginning. A negative OFFSET specifies +placement at that many characters counting backwards from the end of +the string. A positive OFFSET greater than the length of SCALAR +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 actually implemented in terms of either Perl's or system's +fread() call. To get a true read(2) system call, see C. Note the I: depending on the status of the filehandle, 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 characters, not bytes. +pragma, L), the I/O will operate on UTF-8 encoded Unicode +characters, not bytes. Similarly for the C<:encoding> pragma: +in that case pretty much any characters can be read. =item readdir DIRHANDLE @@ -3809,6 +4017,21 @@ operator is discussed in more detail in L. $line = ; $line = readline(*STDIN); # same thing +If readline encounters an operating system error, C<$!> will be set with the +corresponding error message. It can be helpful to check C<$!> when you are +reading from filehandles you don't trust, such as a tty or a socket. The +following example uses the operator form of C, and takes the necessary +steps to ensure that C was successful. + + for (;;) { + undef $!; + unless (defined( $line = <> )) { + die $! if $!; + last; # reached EOF + } + # ... + } + =item readlink EXPR =item readlink @@ -3844,7 +4067,9 @@ 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<:utf8> I/O layer (see the C -pragma, L), the I/O will operate on characters, not bytes. +pragma, L), the I/O will operate on UTF-8 encoded Unicode +characters, not bytes. Similarly for the C<:encoding> pragma: +in that case pretty much any characters can be read. =item redo LABEL @@ -3888,7 +4113,8 @@ C work. =item ref -Returns a true value if EXPR is a reference, false otherwise. If EXPR +Returns a non-empty string if EXPR is a reference, the empty +string otherwise. If EXPR is not specified, C<$_> will be used. The value returned depends on the type of thing the reference is a reference to. Builtin types include: @@ -3954,32 +4180,42 @@ version should be used instead. Otherwise, demands that a library file be included if it hasn't already been included. The file is included via the do-FILE mechanism, which is -essentially just a variety of C. Has semantics similar to the following -subroutine: +essentially just a variety of C. Has semantics similar to the +following subroutine: sub require { - my($filename) = @_; - return 1 if $INC{$filename}; - my($realfilename,$result); - ITER: { - foreach $prefix (@INC) { - $realfilename = "$prefix/$filename"; - if (-f $realfilename) { - $INC{$filename} = $realfilename; - $result = do $realfilename; - last ITER; - } - } - die "Can't find $filename in \@INC"; - } - delete $INC{$filename} if $@ || !$result; - die $@ if $@; - die "$filename did not return true value" unless $result; - return $result; + my ($filename) = @_; + if (exists $INC{$filename}) { + return 1 if $INC{$filename}; + die "Compilation failed in require"; + } + my ($realfilename,$result); + ITER: { + foreach $prefix (@INC) { + $realfilename = "$prefix/$filename"; + if (-f $realfilename) { + $INC{$filename} = $realfilename; + $result = do $realfilename; + last ITER; + } + } + die "Can't find $filename in \@INC"; + } + if ($@) { + $INC{$filename} = undef; + die $@; + } elsif (!$result) { + delete $INC{$filename}; + die "$filename did not return true value"; + } else { + return $result; + } } Note that the file will not be included twice under the same specified -name. The file must return true as the last statement to indicate +name. + +The file must return true as the last statement to indicate successful execution of any initialization code, so it's customary to end such a file with C<1;> unless you're sure it'll return true otherwise. But it's better just to put the C<1;>, in case you add more @@ -4009,6 +4245,15 @@ will complain about not finding "F" there. In this case you can do: eval "require $class"; +Now that you understand how C looks for files in the case of +a bareword argument, there is a little extra functionality going on +behind the scenes. Before C looks for a "F<.pm>" extension, +it will first look for a filename with a "F<.pmc>" extension. A file +with this extension is assumed to be Perl bytecode generated by +L. If this file is found, and it's modification +time is newer than a coinciding "F<.pm>" non-compiled file, it will be +loaded in place of that non-compiled file ending in a "F<.pm>" extension. + You can also insert hooks into the import facility, by putting directly Perl code into the @INC array. There are three forms of hooks: subroutine references, array references and blessed objects. @@ -4115,6 +4360,8 @@ in the opposite order. undef $/; # for efficiency of <> print scalar reverse <>; # character tac, last line tsrif +Used without arguments in scalar context, reverse() reverses C<$_>. + This operator is also handy for inverting a hash, although there are some caveats. If a value is duplicated in the original hash, only one of those can be represented as a key in the inverted hash. Also, this has to @@ -4140,9 +4387,9 @@ last occurrence at or before that position. =item rmdir -Deletes the directory specified by FILENAME if that directory is empty. If it -succeeds it returns true, otherwise it returns false and sets C<$!> (errno). If -FILENAME is omitted, uses C<$_>. +Deletes the directory specified by FILENAME if that directory is +empty. If it succeeds it returns true, otherwise it returns false and +sets C<$!> (errno). If FILENAME is omitted, uses C<$_>. =item s/// @@ -4303,7 +4550,8 @@ You can effect a sleep of 250 milliseconds this way: select(undef, undef, undef, 0.25); Note that whether C. B: One should not attempt to mix buffered I/O (like C or ) with C