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
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 despite what may be implied in I<"Programming Perl">
-(the Camel) or elsewhere C<:raw> is I<not> 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<not> the simply inverse of C<:crlf>
-- other layers which would affect binary nature of the stream are
I<also> disabled. See L<PerlIO>, L<perlrun> and the discussion about the
PERLIO environment variable.
If you chomp a list, each element is chomped, and the total number of
characters removed is returned.
+If the C<encoding> 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<chomp $cwd = `pwd`;>
is interpreted as C<(chomp $cwd) = `pwd`;>, rather than as
Returns the character represented by that NUMBER in the character set.
For example, C<chr(65)> 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<encoding>).
+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<encoding>).
If NUMBER is omitted, uses C<$_>.
C<open>.) However, an explicit C<close> on an input file resets the line
counter (C<$.>), while the implicit close done by C<open> does not.
-If the file handle came from a piped open C<close> 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<close> 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<$?>.
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 C<tie>d hash or array may not necessarily return anything.
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<REMOTE> 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
=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<Socket> 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<undef> 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<i> (or C<I>) 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
$now_string = gmtime; # e.g., "Thu Oct 13 04:54:34 1994"
-Also see the C<timegm> function provided by the C<Time::Local> module,
-and the strftime(3) function available via the POSIX module.
+If you need local time instead of GMT use the L</localtime> builtin.
+See also the C<timegm> function provided by the C<Time::Local> module,
+and the strftime(3) and mktime(3) functions available via the L<POSIX> module.
-This scalar value is B<not> locale dependent (see L<perllocale>), but
-is instead a Perl builtin. Also see the C<Time::Local> 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<perllocale>)
-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<not> locale dependent (see L<perllocale>), but is
+instead a Perl builtin. To get somewhat similar but locale dependent date
+strings, see the example in L</localtime>.
=item goto LABEL
or another C<grep>) 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<grep> appears (because it has
+been declared with C<my $_>) 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</map> for a list composed of the results of the BLOCK or EXPR.
=item hex EXPR
$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<REMOTE> 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
Attacks">).
As a side effect, calling keys() resets the HASH's internal iterator,
-see L</each>.
+see L</each>. (In particular, calling keys() in void context resets
+the iterator with no other overhead.)
Here is yet another way to print your environment:
$now_string = localtime; # e.g., "Thu Oct 13 04:54:34 1994"
-This scalar value is B<not> locale dependent, see L<perllocale>, but
-instead a Perl builtin. Also see the C<Time::Local> 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<perllocale>) and try for example:
+This scalar value is B<not> locale dependent but is a Perl builtin. For GMT
+instead of local time use the L</gmtime> builtin. See also the
+C<Time::Local> module (to convert the second, minutes, hours, ... back to
+the integer value returned by time()), and the L<POSIX> 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<perllocale>) 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.
most cases. See also L</grep> 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<map> appears (because it has
+been declared with C<my $_>) 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<map { ...> 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
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) || ..
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
}
}
+See L<perliol/> 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
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<< '<&=X' >>, where C<X> is a number or a filehandle,
-then Perl will do an equivalent of C's C<fdopen> of that file
-descriptor (and not call L<dup(2)>); this is more parsimonious
-of file descriptors. For example:
+If you specify C<< '<&=X' >>, where C<X> is a file descriptor number
+or a filehandle, then Perl will do an equivalent of C's C<fdopen> of
+that file descriptor (and not call L<dup(2)>); this is more
+parsimonious of file descriptors. For example:
# open for input, reusing the fileno of $fd
open(FILEHANDLE, "<&=$fd")
open(FH, ">>&=OLDFH")
-Being parsimonious on filehandles is useful (besides being
-parsimonious) also for example when something is dependent
-on the file descriptors, like for example locking using flock().
-If you do just a C<< open(A, '>>&B') >>, the filehandle A will not
-have the file descriptor as B has, 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.
+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 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<PerlIO>.
+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<perl -V> and looking for C<useperlio=> line. If C<useperlio>
multi-threaded application. The C<unique> 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<our $x : unique>
+also has the effect of C<our @x : unique; our %x : unique>. This may be
+subject to change.
+
=item pack TEMPLATE,LIST
Takes a LIST of values and converts it into a string using the rules
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.
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.
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<E<gt>> and C<E<lt>> 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
length. A NULL pointer is created if the corresponding value for C<p> or
C<P> is C<undef>, 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
=item *
The integer types C<s>, C<S>, C<l>, and C<L> 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<l> does mean
exactly 32 bits, the native C<long> (as seen by the local C compiler)
may be larger. This is an issue mainly in 64-bit platforms. You can
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<n>, C<N>,
-C<v>, and C<V>, their byte endianness and size are known.
+If you want portable packed integers you can either use the formats
+C<n>, C<N>, C<v>, and C<V>, or you can use the C<E<gt>> and C<E<lt>>
+modifiers. These modifiers are only available as of perl 5.8.5.
See also L<perlport>.
=item *
+All integer and floating point formats as well as C<p> and C<P> and
+C<()>-groups may be followed by the C<E<gt>> or C<E<lt>> modifiers
+to force big- or little- endian byte-order, respectively.
+This is especially useful, since C<n>, C<N>, C<v> and C<V> 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<E<gt>> or C<E<lt>> 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<E<gt>> or C<E<lt>> 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<E<gt>> or C<E<lt>> 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
arithmetic (as the endian-ness of the memory representation is not part
of the IEEE spec). See also L<perlport>.
-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<unpack("f", pack("f", $foo)>) will not in general
-equal $foo).
+If you know exactly what you're doing, you can use the C<E<gt>> or C<E<lt>>
+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<unpack("f", pack("f", $foo)>)
+will not in general equal $foo).
=item *
-If the pattern begins with a C<U>, the resulting string will be treated
-as Unicode-encoded. You can force UTF8 encoding on in a string with an
-initial C<U0>, 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<C0> (or anything else) to force Perl not to UTF8 encode your
-string, and then follow this with a C<U*> somewhere in your pattern.
+If the pattern begins with a C<U>, 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<U0>, 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<C0> (or anything else) to force Perl
+not to UTF-8 encode your string, and then follow this with a C<U*>
+somewhere in your pattern.
=item *
=item *
+C<n>, C<N>, C<v> and C<V> 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
-a C<!> modifier and a repeat count must follow immediately.
+modifiers and a repeat count must follow immediately.
=item *
# 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<l<', -42, 4711);
+ # pack little-endian 16- and 32-bit signed integers
+ $foo = pack('(sl)<', -42, 4711);
+ # exactly the same
+
The same template may generally also be used in unpack().
=item package NAMESPACE
=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:
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<eval>. Has semantics similar to the following
-subroutine:
+essentially just a variety of C<eval>. 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
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
select(undef, undef, undef, 0.25);
Note that whether C<select> gets restarted after signals (say, SIGALRM)
-is implementation-dependent.
+is implementation-dependent. See also L<perlport> for notes on the
+portability of C<select>.
B<WARNING>: One should not attempt to mix buffered I/O (like C<read>
or <FH>) with C<select>, except as permitted by POSIX, and even
=item split
-Splits a string into a list of strings and returns that list. By default,
-empty leading fields are preserved, and empty trailing ones are deleted.
+Splits the string EXPR into a list of strings and returns that list. By
+default, empty leading fields are preserved, and empty trailing ones are
+deleted.
In scalar context, returns the number of fields found and splits into
the C<@_> array. Use of split in scalar context is deprecated, however,
= stat($filename);
Not all fields are supported on all filesystem types. Here are the
-meaning of the fields:
+meanings of the fields:
0 dev device number of filesystem
1 ino inode number
(The epoch was at 00:00 January 1, 1970 GMT.)
-(*) The ctime field is non-portable, in particular you cannot expect
+(*) The ctime field is non-portable. In particular, you cannot expect
it to be a "creation time", see L<perlport/"Files and Filesystems">
for details.
-If stat is passed the special filehandle consisting of an underline, no
+If C<stat> is passed the special filehandle consisting of an underline, no
stat is done, but the current contents of the stat structure from the
-last stat or filetest are returned. Example:
+last C<stat>, C<lstat>, or filetest are returned. Example:
if (-x $file && (($d) = stat(_)) && $d < 0) {
print "$file is executable NFS file\n";
$is_setgid = S_ISDIR($mode);
You could write the last two using the C<-u> and C<-d> operators.
-The commonly available S_IF* constants are
+The commonly available C<S_IF*> constants are
# Permissions: read, write, execute, for user, group, others.
S_IREAD S_IWRITE S_IEXEC
-and the S_IF* functions are
+and the C<S_IF*> functions are
S_IMODE($mode) the part of $mode containing the permission bits
and the setuid/setgid/sticky bits
which can be bit-anded with e.g. S_IFREG
or with the following functions
- # The operators -f, -d, -l, -b, -c, -p, and -s.
+ # The operators -f, -d, -l, -b, -c, -p, and -S.
S_ISREG($mode) S_ISDIR($mode) S_ISLNK($mode)
S_ISBLK($mode) S_ISCHR($mode) S_ISFIFO($mode) S_ISSOCK($mode)
S_ISENFMT($mode) S_ISWHT($mode)
See your native chmod(2) and stat(2) documentation for more details
-about the S_* constants. To get status info for a symbolic link
+about the C<S_*> constants. To get status info for a symbolic link
instead of the target file behind the link, use the C<lstat> function.
=item study SCALAR
parts of the EXPR and return what was there before in one operation,
just as you can with splice().
-If the lvalue returned by substr is used after the EXPR is changed in
-any way, the behaviour may not be as expected and is subject to change.
-This caveat includes code such as C<print(substr($foo,$a,$b)=$bar)> or
-C<(substr($foo,$a,$b)=$bar)=$fud> (where $foo is changed via the
-substring assignment, and then the substr is used again), or where a
-substr() is aliased via a C<foreach> loop or passed as a parameter or
-a reference to it is taken and then the alias, parameter, or deref'd
-reference either is used after the original EXPR has been changed or
-is assigned to and then used a second time.
+Note that the lvalue returned by by the 3-arg version of substr() acts as
+a 'magic bullet'; each time it is assigned to, it remembers which part
+of the original string is being modified; for example:
+
+ $x = '1234';
+ for (substr($x,1,2)) {
+ $_ = 'a'; print $x,"\n"; # prints 1a4
+ $_ = 'xyz'; print $x,"\n"; # prints 1xyz4
+ $x = '56789';
+ $_ = 'pq'; print $x,"\n"; # prints 5pq9
+ }
+
+
+Prior to Perl version 5.9.1, the result of using an lvalue multiple times was
+unspecified.
=item symlink OLDFILE,NEWFILE
Some of the most common values are C<O_RDONLY> for opening the file in
read-only mode, C<O_WRONLY> for opening the file in write-only mode,
-and C<O_RDWR> for opening the file in read-write mode, and.
+and C<O_RDWR> for opening the file in read-write mode.
For historical reasons, some values work on almost every system
supported by perl: zero means read-only, one means write-only, and two
In many systems the C<O_EXCL> flag is available for opening files in
exclusive mode. This is B<not> locking: exclusiveness means here that
-if the file already exists, sysopen() fails. The C<O_EXCL> wins
-C<O_TRUNC>.
+if the file already exists, sysopen() fails. C<O_EXCL> may not work
+on network filesystems, and has no effect unless the C<O_CREAT> flag
+is set as well. Setting C<O_CREAT|O_EXCL> prevents the file from
+being opened if it is a symbolic link. It does not protect against
+symbolic links in the file's path.
-Sometimes you may want to truncate an already-existing file: C<O_TRUNC>.
+Sometimes you may want to truncate an already-existing file. This
+can be done using the C<O_TRUNC> flag. The behavior of
+C<O_TRUNC> with C<O_RDONLY> is undefined.
You should seldom if ever use C<0644> as argument to C<sysopen>, because
that takes away the user's option to have a more permissive umask.
Like C<exec>, C<system> allows you to lie to a program about its name if
you use the C<system PROGRAM LIST> syntax. Again, see L</exec>.
-Because C<system> and backticks block C<SIGINT> and C<SIGQUIT>,
-killing the program they're running doesn't actually interrupt
-your program.
+Since C<SIGINT> and C<SIGQUIT> are ignored during the execution of
+C<system>, if you expect your program to terminate on receipt of these
+signals you will need to arrange to do so yourself based on the return
+value.
@args = ("command", "arg1", "arg2");
system(@args) == 0
You can check all the failure possibilities by inspecting
C<$?> like this:
- $exit_value = $? >> 8;
- $signal_num = $? & 127;
- $dumped_core = $? & 128;
+ if ($? == -1) {
+ print "failed to execute: $!\n";
+ }
+ elsif ($? & 127) {
+ printf "child died with signal %d, %s coredump\n",
+ ($? & 127), ($? & 128) ? 'with' : 'without';
+ }
+ else {
+ printf "child exited with value %d\n", $? >> 8;
+ }
or more portably by using the W*() calls of the POSIX extension;
see L<perlport> for more information.
EXISTS this, key
FIRSTKEY this
NEXTKEY this, lastkey
+ SCALAR this
DESTROY this
UNTIE this
Unix touch(1) command when the files I<already exist>.
#!/usr/bin/perl
- $now = time;
- utime $now, $now, @ARGV;
-
-B<Note:> Under NFS, touch(1) uses the time of the NFS server, not
-the time of the local machine. If there is a time synchronization
-problem, the NFS server and local machine will have different times.
+ $atime = $mtime = time;
+ utime $atime, $mtime, @ARGV;
Since perl 5.7.2, if the first two elements of the list are C<undef>, then
the utime(2) function in the C library will be called with a null second
utime undef, undef, @ARGV;
+Under NFS this will use the time of the NFS server, not the time of
+the local machine. If there is a time synchronization problem, the
+NFS server and local machine will have different times. The Unix
+touch(1) command will in fact normally use this form instead of the
+one shown in the first example.
+
+Note that only passing one of the first two elements as C<undef> will
+be equivalent of passing it as 0 and will not have the same effect as
+described when they are both C<undef>. This case will also trigger an
+uninitialized warning.
+
=item values HASH
Returns a list consisting of all the values of the named hash.
for security reasons (see L<perlsec/"Algorithmic Complexity Attacks">).
As a side effect, calling values() resets the HASH's internal iterator,
-see L</each>.
+see L</each>. (In particular, calling values() in void context resets
+the iterator with no other overhead.)
Note that the values are not copied, which means modifying them will
modify the contents of the hash:
to try to write off the beginning of the string (i.e. negative OFFSET).
The string should not contain any character with the value > 255 (which
-can only happen if you're using UTF8 encoding). If it does, it will be
-treated as something which is not UTF8 encoded. When the C<vec> was
+can only happen if you're using UTF-8 encoding). If it does, it will be
+treated as something which is not UTF-8 encoded. When the C<vec> was
assigned to, other parts of your program will also no longer consider the
-string to be UTF8 encoded. In other words, if you do have such characters
+string to be UTF-8 encoded. In other words, if you do have such characters
in your string, vec() will operate on the actual byte string, and not the
conceptual character string.
=item wantarray
-Returns true if the context of the currently executing subroutine is
-looking for a list value. Returns false if the context is looking
-for a scalar. Returns the undefined value if the context is looking
-for no value (void context).
+Returns true if the context of the currently executing subroutine or
+eval() block is looking for a list value. Returns false if the context is
+looking for a scalar. Returns the undefined value if the context is
+looking for no value (void context).
return unless defined wantarray; # don't bother doing more
my @a = complex_calculation();