operator takes one argument, either a filename, a filehandle, or a dirhandle,
and tests the associated file to see if something is true about it. If the
argument is omitted, tests C<$_>, except for C<-t>, which tests STDIN.
-Unless otherwise documented, it returns C<1> for true and C<''> for false, or
-the undefined value if the file doesn't exist. Despite the funny
-names, precedence is the same as any other named unary operator. The
-operator may be any of:
+Unless otherwise documented, it returns C<1> for true and C<''> for false.
+If the file doesn't exist or can't be examined, it returns C<undef> and
+sets C<$!> (errno). Despite the funny names, precedence is the same as any
+other named unary operator. The operator may be any of:
-r File is readable by effective uid/gid.
-w File is writable by effective uid/gid.
=for Pod::Functions get context of the current subroutine call
-Returns the context of the current subroutine call. In scalar context,
-returns the caller's package name if there I<is> a caller (that is, if
+Returns the context of the current pure perl subroutine call. In scalar
+context, returns the caller's package name if there I<is> a caller (that is, if
we're in a subroutine or C<eval> or C<require>) and the undefined value
-otherwise. In list context, returns
+otherwise. caller never returns XS subs and they are skipped. The next pure
+perl sub will appear instead of the XS sub in caller's return values. In list
+context, caller returns
# 0 1 2
($package, $filename, $line) = caller;
$wantarray, $evaltext, $is_require, $hints, $bitmask, $hinthash)
= caller($i);
-Here $subroutine may be C<(eval)> if the frame is not a subroutine
-call, but an C<eval>. In such a case additional elements $evaltext and
+Here, $subroutine is the function that the caller called (rather than the
+function containing the caller). Note that $subroutine may be C<(eval)> if
+the frame is not a subroutine call, but an C<eval>. In such a case
+additional elements $evaltext and
C<$is_require> are set: C<$is_require> is true if the frame is created by a
C<require> or C<use> statement, $evaltext contains the text of the
C<eval EXPR> statement. In particular, for an C<eval BLOCK> statement,
use POSIX qw(sysconf _PC_CHOWN_RESTRICTED);
$can_chown_giveaway = not sysconf(_PC_CHOWN_RESTRICTED);
-Portability issues: L<perlport/chmod>.
+Portability issues: L<perlport/chown>.
=item chr NUMBER
X<chr> X<character> X<ASCII> X<Unicode>
reasons, this call is restricted to the superuser. If FILENAME is
omitted, does a C<chroot> to C<$_>.
+B<NOTE:> It is good security practice to do C<chdir("/")> (to the root
+directory) immediately after a C<chroot()>.
+
Portability issues: L<perlport/chroot>.
=item close FILEHANDLE
delete() may also be used on arrays and array slices, but its behavior is less
straightforward. Although exists() will return false for deleted entries,
deleting array elements never changes indices of existing values; use shift()
-or splice() for that. However, if all deleted elements fall at the end of an
+or splice() for that. However, if any deleted elements fall at the end of an
array, the array's size shrinks to the position of the highest element that
-still tests true for exists(), or to 0 if none do.
+still tests true for exists(), or to 0 if none do. In other words, an
+array won't have trailing nonexistent elements after a delete.
B<WARNING:> Calling delete on array values is deprecated and likely to
be removed in a future version of Perl.
C<next>, C<last>, or C<redo> cannot be used to leave or restart the block.
See L<perlsyn> for alternative strategies.
-=item do SUBROUTINE(LIST)
-X<do>
-
-This form of subroutine call is deprecated. SUBROUTINE can be a bareword
-or scalar variable.
-
=item do EXPR
X<do>
C<keys>, and C<values>. The iterator is implicitly reset when C<each> has
reached the end as just described; it can be explicitly reset by calling
C<keys> or C<values> on the hash or array. If you add or delete a hash's
-elements while iterating over it, entries may be skipped or duplicated--so
-don't do that. Exception: In the current implementation, it is always safe
-to delete the item most recently returned by C<each()>, so the following
-code works properly:
+elements while iterating over it, the effect on the iterator is
+unspecified; for example, entries may be skipped or duplicated--so don't
+do that. Exception: It is always safe to delete the item most recently
+returned by C<each()>, so the following code works properly:
while (($key, $value) = each %hash) {
print $key, "\n";
warnings to STDERR, nor does it stuff the text of warning messages into C<$@>.
To do either of those, you have to use the C<$SIG{__WARN__}> facility, or
turn off warnings inside the BLOCK or EXPR using S<C<no warnings 'all'>>.
-See L</warn>, L<perlvar>, L<warnings> and L<perllexwarn>.
+See L</warn>, L<perlvar>, and L<warnings>.
Note that, because C<eval> traps otherwise-fatal errors, it is useful for
determining whether a particular feature (such as C<socket> or C<symlink>)
exec ('foo') or print STDERR "couldn't exec foo: $!";
{ exec ('foo') }; print STDERR "couldn't exec foo: $!";
-If there is more than one argument in LIST, or if LIST is an array
-with more than one value, calls execvp(3) with the arguments in LIST.
-If there is only one scalar argument or an array with one element in it,
-the argument is checked for shell metacharacters, and if there are any,
-the entire argument is passed to the system's command shell for parsing
-(this is C</bin/sh -c> on Unix platforms, but varies on other platforms).
-If there are no shell metacharacters in the argument, it is split into
-words and passed directly to C<execvp>, which is more efficient.
-Examples:
+If there is more than one argument in LIST, this calls execvp(3) with the
+arguments in LIST. If there is only one element in LIST, the argument is
+checked for shell metacharacters, and if there are any, the entire
+argument is passed to the system's command shell for parsing (this is
+C</bin/sh -c> on Unix platforms, but varies on other platforms). If
+there are no shell metacharacters in the argument, it is split into words
+and passed directly to C<execvp>, which is more efficient. Examples:
exec '/bin/echo', 'Your arguments are: ', @ARGV;
exec "sort $outfile | uniq";
system C library. In list context, the return values from the
various get routines are as follows:
- ($name,$passwd,$uid,$gid,
- $quota,$comment,$gcos,$dir,$shell,$expire) = getpw*
- ($name,$passwd,$gid,$members) = getgr*
- ($name,$aliases,$addrtype,$length,@addrs) = gethost*
- ($name,$aliases,$addrtype,$net) = getnet*
- ($name,$aliases,$proto) = getproto*
- ($name,$aliases,$port,$proto) = getserv*
+ # 0 1 2 3 4
+ ( $name, $passwd, $gid, $members ) = getgr*
+ ( $name, $aliases, $addrtype, $net ) = getnet*
+ ( $name, $aliases, $port, $proto ) = getserv*
+ ( $name, $aliases, $proto ) = getproto*
+ ( $name, $aliases, $addrtype, $length, @addrs ) = gethost*
+ ( $name, $passwd, $uid, $gid, $quota,
+ $comment, $gcos, $dir, $shell, $expire ) = getpw*
+ # 5 6 7 8 9
(If the entry doesn't exist you get an empty list.)
=for Pod::Functions send a signal to a process or process group
-Sends a signal to a list of processes. Returns the number of
-processes successfully signaled (which is not necessarily the
-same as the number actually killed).
+Sends a signal to a list of processes. Returns the number of arguments
+that were successfully used to signal (which is not necessarily the same
+as the number of processes actually killed, e.g. where a process group is
+killed).
$cnt = kill 'HUP', $child1, $child2;
kill 'KILL', @goners;
See L<perlipc/"Signals"> 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.
+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.
=item If C<use bytes> is in effect:
-The results follow ASCII semantics. Only characters C<A-Z> change, to C<a-z>
-respectively.
+The results follow ASCII rules. Only the characters C<A-Z> change,
+to C<a-z> respectively.
=item Otherwise, if C<use locale> (but not C<use locale ':not_characters'>) is in effect:
Respects current LC_CTYPE locale for code points < 256; and uses Unicode
-semantics for the remaining code points (this last can only happen if
+rules for the remaining code points (this last can only happen if
the UTF8 flag is also set). See L<perllocale>.
-A deficiency in this is that case changes that cross the 255/256
+Starting in v5.20, Perl wil use full Unicode rules if the locale is
+UTF-8. Otherwise, there is a deficiency in this scheme, which 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<use locale>, the lower case of U+1E9E is
+LETTER SHARP S (U+1E9E) in Unicode rules is U+00DF (on ASCII
+platforms). But under C<use locale> (prior to v5.20 or not a UTF-8
+locale), 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
=item Otherwise, If EXPR has the UTF8 flag set:
-Unicode semantics are used for the case change.
+Unicode rules are used for the case change.
=item Otherwise, if C<use feature 'unicode_strings'> or C<use locale ':not_characters'> is in effect:
-Unicode semantics are used for the case change.
+Unicode rules are used for the case change.
=item Otherwise:
-ASCII semantics are used for the case change. The lowercase of any character
+ASCII rules are used for the case change. The lowercase of any character
outside the ASCII range is the character itself.
=back
everyone happy.
To recursively create a directory structure, look at
-the C<mkpath> function of the L<File::Path> module.
+the C<make_path> function of the L<File::Path> module.
=item msgctl ID,CMD,ARG
X<msgctl>
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 the C<fields> pragma,
+evolving. TYPE may be a bareword, a constant declared
+with C<use constant>, or C<__PACKAGE__>. It is
+currently bound to the use of the C<fields> pragma,
and attributes are handled using the C<attributes> pragma, or starting
from Perl 5.8.0 also via the C<Attribute::Handlers> module. See
L<perlsub/"Private Variables via my()"> for details, and L<fields>,
considered a symbolic reference, so C<use strict "refs"> should I<not> 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<my> or C<state>--will not work for this
-purpose; so if you're using C<my> or C<state>, 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.
modules that can help with that problem)) always check
the return value from opening a file.
+The filehandle will be closed when its reference count reaches zero.
+If it is a lexically scoped variable declared with C<my>, that usually
+means the end of the enclosing scope. However, this automatic close
+does not check for errors, so it is better to explicitly close
+filehandles, especially those used for writing:
+
+ close($handle)
+ || warn "close failed: $!";
+
+An older style is to use a bareword as the filehandle, as
+
+ open(FH, "<", "input.txt")
+ or die "cannot open < input.txt: $!";
+
+Then you can use C<FH> as the filehandle, in C<< close FH >> and C<<
+<FH> >> and so on. Note that it's a global variable, so this form is
+not recommended in new code.
+
+As a shortcut a one-argument call takes the filename from the global
+scalar variable of the same name as the filehandle:
+
+ $ARTICLE = 100;
+ open(ARTICLE) or die "Can't find article $ARTICLE: $!\n";
+
+Here C<$ARTICLE> must be a global (package) scalar variable - not one
+declared with C<my> or C<state>.
+
As a special case the three-argument form with a read/write mode and the third
argument being C<undef>:
General examples:
- $ARTICLE = 100;
- open(ARTICLE) or die "Can't find article $ARTICLE: $!\n";
- while (<ARTICLE>) {...
-
open(LOG, ">>/usr/spool/news/twitlog"); # (log is reserved)
# if the open fails, output is discarded
seek(HANDLE, 0, 0);
print "File contains: ", <HANDLE>;
-Using the constructor from the C<IO::Handle> package (or one of its
-subclasses, such as C<IO::File> or C<IO::Socket>), you can generate anonymous
-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: $!";
- $first = <$handle>
- or return (); # Automatically closed here.
- mung($first) or die "mung failed"; # Or here.
- return (first, <$handle>) if $ALL; # Or here.
- return $first; # Or here.
- }
-
-B<WARNING:> The previous example has a bug because the automatic
-close that happens when the refcount on C<handle> reaches zero does not
-properly detect and report failures. I<Always> close the handle
-yourself and inspect the return value.
-
- close($handle)
- || warn "close failed: $!";
-
See L</seek> for some details about mixing reading and writing.
Portability issues: L<perlport/open>.
! sSlLiI Forces native (short, long, int) sizes instead
of fixed (16-/32-bit) sizes.
- xX Make x and X act as alignment commands.
+ ! xX Make x and X act as alignment commands.
- nNvV Treat integers as signed instead of unsigned.
+ ! nNvV Treat integers as signed instead of unsigned.
- @. Specify position as byte offset in the internal
+ ! @. Specify position as byte offset in the internal
representation of the packed string. Efficient
but dangerous.
=for Pod::Functions find out the type of thing being referenced
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.
+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:
SCALAR
VSTRING
Regexp
-If the referenced object has been blessed into a package, then that package
-name is returned instead. You can think of C<ref> as a C<typeof> operator.
+You can think of C<ref> as a C<typeof> operator.
if (ref($r) eq "HASH") {
print "r is a reference to a hash.\n";
The result C<Regexp> indicates that the argument is a regular expression
resulting from C<qr//>.
+If the referenced object has been blessed into a package, then that package
+name is returned instead. But don't use that, as it's now considered
+"bad practice". For one reason, an object could be using a class called
+C<Regexp> or C<IO>, or even C<HASH>. Also, C<ref> doesn't take into account
+subclasses, like C<isa> does.
+
+Instead, use C<blessed> (in the L<Scalar::Util> module) for boolean
+checks, C<isa> for specific class checks and C<reftype> (also from
+L<Scalar::Util>) for type checks. (See L<perlobj> for details and a
+C<blessed/isa> example.)
+
See also L<perlref>.
=item rename OLDNAME,NEWNAME
use version;
sub require {
- my ($filename) = @_;
- if ( my $version = eval { version->parse($filename) } ) {
- if ( $version > $^V ) {
+ my ($filename) = @_;
+ if ( my $version = eval { version->parse($filename) } ) {
+ if ( $version > $^V ) {
my $vn = $version->normal;
croak "Perl $vn required--this is only $^V, stopped";
- }
- return 1;
- }
- if (exists $INC{$filename}) {
- return 1 if $INC{$filename};
- croak "Compilation failed in require";
- }
- my ($realfilename,$result);
- ITER: {
- foreach $prefix (@INC) {
- $realfilename = "$prefix/$filename";
- if (-f $realfilename) {
- $INC{$filename} = $realfilename;
- my $caller = caller;
- my $do_as_caller = eval qq{
- package $caller;
- sub { do \$_[0] }
- };
- $result = $do_as_caller->($realfilename);
- last ITER;
- }
- }
- croak "Can't locate $filename in \@INC";
- }
- if ($@) {
- $INC{$filename} = undef;
- croak $@;
- } elsif (!$result) {
- delete $INC{$filename};
- croak "$filename did not return true value";
- } else {
- $! = 0;
- return $result;
- }
+ }
+ return 1;
+ }
+
+ if (exists $INC{$filename}) {
+ return 1 if $INC{$filename};
+ croak "Compilation failed in require";
+ }
+
+ foreach $prefix (@INC) {
+ if (ref($prefix)) {
+ #... do other stuff - see text below ....
+ }
+ # (see text below about possible appending of .pmc
+ # suffix to $filename)
+ my $realfilename = "$prefix/$filename";
+ next if ! -e $realfilename || -d _ || -b _;
+ $INC{$filename} = $realfilename;
+ my $result = do($realfilename);
+ # but run in caller's namespace
+
+ if (!defined $result) {
+ $INC{$filename} = undef;
+ croak $@ ? "$@Compilation failed in require"
+ : "Can't locate $filename: $!\n";
+ }
+ if (!$result) {
+ delete $INC{$filename};
+ croak "$filename did not return true value";
+ }
+ $! = 0;
+ return $result;
+ }
+ croak "Can't locate $filename in \@INC ...";
}
Note that the file will not be included twice under the same specified
unshift(@a,$x,$y) splice(@a,0,0,$x,$y)
$a[$i] = $y splice(@a,$i,1,$y)
-Example, assuming array lengths are passed before arrays:
+C<splice> can be used, for example, to implement n-ary queue processing:
- sub aeq { # compare two list values
- my(@a) = splice(@_,0,shift);
- my(@b) = splice(@_,0,shift);
- return 0 unless @a == @b; # same len?
- while (@a) {
- return 0 if pop(@a) ne pop(@b);
- }
- return 1;
+ sub nary_print {
+ my $n = shift;
+ while (my @next_n = splice @_, 0, $n) {
+ say join q{ -- }, @next_n;
+ }
}
- if (&aeq($len,@foo[1..$len],0+@bar,@bar)) { ... }
+
+ nary_print(3, qw(a b c d e f g h));
+ # prints:
+ # a -- b -- c
+ # d -- e -- f
+ # g -- h
Starting with Perl 5.14, C<splice> can take scalar EXPR, which must hold a
reference to an unblessed array. The argument will be dereferenced
Note that C<sysopen> depends on the fdopen() C library function.
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<sfio>
-library, or perhaps using the POSIX::open() function.
+descriptors than that, consider using the POSIX::open() function.
See L<perlopentut> for a kinder, gentler explanation of opening files.
=for Pod::Functions transliterate a string
The transliteration operator. Same as C<y///>. See
-L<perlop/"Quote and Quote-like Operators">.
+L<perlop/"Quote-Like Operators">.
=item truncate FILEHANDLE,LENGTH
X<truncate>
=for Pod::Functions transliterate a string
The transliteration operator. Same as C<tr///>. See
-L<perlop/"Quote and Quote-like Operators">.
+L<perlop/"Quote-Like Operators">.
=back
=item gt
-=item if
-
=item le
=item lt
=item foreach
+=item if
+
=item unless
=item until