perlfunc.pod
来自「ARM上的如果你对底层感兴趣」· POD 代码 · 共 1,705 行 · 第 1/5 页
POD
1,705 行
the files listed on the command line, i.e., C<eof()> is reasonable to
use inside a C<while (E<lt>E<gt>)> loop to detect the end of only the
last file. Use C<eof(ARGV)> or eof without the parentheses to test
I<EACH> file in a while (E<lt>E<gt>) loop. Examples:
# reset line numbering on each input file
while (<>) {
next if /^\s*#/; # skip comments
print "$.\t$_";
} continue {
close ARGV if eof; # Not eof()!
}
# insert dashes just before last line of last file
while (<>) {
if (eof()) { # check for end of current file
print "--------------\n";
close(ARGV); # close or break; is needed if we
# are reading from the terminal
}
print;
}
Practical hint: you almost never need to use C<eof> in Perl, because the
input operators return false values when they run out of data, or if there
was an error.
=item eval EXPR
=item eval BLOCK
In the first form, the return value of EXPR is parsed and executed as if it
were a little Perl program. The value of the expression (which is itself
determined within scalar context) is first parsed, and if there weren't any
errors, executed in the context of the current Perl program, so that any
variable settings or subroutine and format definitions remain afterwards.
Note that the value is parsed every time the eval executes. If EXPR is
omitted, evaluates C<$_>. This form is typically used to delay parsing
and subsequent execution of the text of EXPR until run time.
In the second form, the code within the BLOCK is parsed only once--at the
same time the code surrounding the eval itself was parsed--and executed
within the context of the current Perl program. This form is typically
used to trap exceptions more efficiently than the first (see below), while
also providing the benefit of checking the code within BLOCK at compile
time.
The final semicolon, if any, may be omitted from the value of EXPR or within
the BLOCK.
In both forms, the value returned is the value of the last expression
evaluated inside the mini-program; a return statement may be also used, just
as with subroutines. The expression providing the return value is evaluated
in void, scalar, or list context, depending on the context of the eval itself.
See L</wantarray> for more on how the evaluation context can be determined.
If there is a syntax error or runtime error, or a C<die()> statement is
executed, an undefined value is returned by C<eval()>, and C<$@> is set to the
error message. If there was no error, C<$@> is guaranteed to be a null
string. Beware that using C<eval()> neither silences perl from printing
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. See
L</warn> and L<perlvar>.
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()>)
is implemented. It is also Perl's exception trapping mechanism, where
the die operator is used to raise exceptions.
If the code to be executed doesn't vary, you may use the eval-BLOCK
form to trap run-time errors without incurring the penalty of
recompiling each time. The error, if any, is still returned in C<$@>.
Examples:
# make divide-by-zero nonfatal
eval { $answer = $a / $b; }; warn $@ if $@;
# same thing, but less efficient
eval '$answer = $a / $b'; warn $@ if $@;
# a compile-time error
eval { $answer = }; # WRONG
# a run-time error
eval '$answer ='; # sets $@
When using the C<eval{}> form as an exception trap in libraries, you may
wish not to trigger any C<__DIE__> hooks that user code may have
installed. You can use the C<local $SIG{__DIE__}> construct for this
purpose, as shown in this example:
# a very private exception trap for divide-by-zero
eval { local $SIG{'__DIE__'}; $answer = $a / $b; };
warn $@ if $@;
This is especially significant, given that C<__DIE__> hooks can call
C<die()> again, which has the effect of changing their error messages:
# __DIE__ hooks may modify error messages
{
local $SIG{'__DIE__'} =
sub { (my $x = $_[0]) =~ s/foo/bar/g; die $x };
eval { die "foo lives here" };
print $@ if $@; # prints "bar lives here"
}
With an C<eval()>, you should be especially careful to remember what's
being looked at when:
eval $x; # CASE 1
eval "$x"; # CASE 2
eval '$x'; # CASE 3
eval { $x }; # CASE 4
eval "\$$x++"; # CASE 5
$$x++; # CASE 6
Cases 1 and 2 above behave identically: they run the code contained in
the variable C<$x>. (Although case 2 has misleading double quotes making
the reader wonder what else might be happening (nothing is).) Cases 3
and 4 likewise behave in the same way: they run the code C<'$x'>, which
does nothing but return the value of C<$x>. (Case 4 is preferred for
purely visual reasons, but it also has the advantage of compiling at
compile-time instead of at run-time.) Case 5 is a place where
normally you I<WOULD> like to use double quotes, except that in this
particular situation, you can just use symbolic references instead, as
in case 6.
=item exec LIST
=item exec PROGRAM LIST
The C<exec()> function executes a system command I<AND NEVER RETURNS> -
use C<system()> instead of C<exec()> if you want it to return. It fails and
returns FALSE only if the command does not exist I<and> it is executed
directly instead of via your system's command shell (see below).
Since it's a common mistake to use C<exec()> instead of C<system()>, Perl
warns you if there is a following statement which isn't C<die()>, C<warn()>,
or C<exit()> (if C<-w> is set - but you always do that). If you
I<really> want to follow an C<exec()> with some other statement, you
can use one of these styles to avoid the warning:
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. Note:
C<exec()> and C<system()> do not flush your output buffer, so you may need to
set C<$|> to avoid lost output. Examples:
exec '/bin/echo', 'Your arguments are: ', @ARGV;
exec "sort $outfile | uniq";
If you don't really want to execute the first argument, but want to lie
to the program you are executing about its own name, you can specify
the program you actually want to run as an "indirect object" (without a
comma) in front of the LIST. (This always forces interpretation of the
LIST as a multivalued list, even if there is only a single scalar in
the list.) Example:
$shell = '/bin/csh';
exec $shell '-sh'; # pretend it's a login shell
or, more directly,
exec {'/bin/csh'} '-sh'; # pretend it's a login shell
When the arguments get executed via the system shell, results will
be subject to its quirks and capabilities. See L<perlop/"`STRING`">
for details.
Using an indirect object with C<exec()> or C<system()> is also more secure.
This usage forces interpretation of the arguments as a multivalued list,
even if the list had just one argument. That way you're safe from the
shell expanding wildcards or splitting up words with whitespace in them.
@args = ( "echo surprise" );
system @args; # subject to shell escapes
# if @args == 1
system { $args[0] } @args; # safe even with one-arg list
The first version, the one without the indirect object, ran the I<echo>
program, passing it C<"surprise"> an argument. The second version
didn't--it tried to run a program literally called I<"echo surprise">,
didn't find it, and set C<$?> to a non-zero value indicating failure.
Note that C<exec()> will not call your C<END> blocks, nor will it call
any C<DESTROY> methods in your objects.
=item exists EXPR
Returns TRUE if the specified hash key exists in its hash array, even
if the corresponding value is undefined.
print "Exists\n" if exists $array{$key};
print "Defined\n" if defined $array{$key};
print "True\n" if $array{$key};
A hash element can be TRUE only if it's defined, and defined if
it exists, but the reverse doesn't necessarily hold true.
Note that the EXPR can be arbitrarily complicated as long as the final
operation is a hash key lookup:
if (exists $ref->{"A"}{"B"}{$key}) { ... }
Although the last element will not spring into existence just because its
existence was tested, intervening ones will. Thus C<$ref-E<gt>{"A"}>
C<$ref-E<gt>{"B"}> will spring into existence due to the existence
test for a $key element. This autovivification may be fixed in a later
release.
=item exit EXPR
Evaluates EXPR and exits immediately with that value. (Actually, it
calls any defined C<END> routines first, but the C<END> routines may not
abort the exit. Likewise any object destructors that need to be called
are called before exit.) Example:
$ans = <STDIN>;
exit 0 if $ans =~ /^[Xx]/;
See also C<die()>. If EXPR is omitted, exits with C<0> status. The only
universally portable values for EXPR are C<0> for success and C<1> for error;
all other values are subject to unpredictable interpretation depending
on the environment in which the Perl program is running.
You shouldn't use C<exit()> to abort a subroutine if there's any chance that
someone might want to trap whatever error happened. Use C<die()> instead,
which can be trapped by an C<eval()>.
All C<END{}> blocks are run at exit time. See L<perlsub> for details.
=item exp EXPR
=item exp
Returns I<e> (the natural logarithm base) to the power of EXPR.
If EXPR is omitted, gives C<exp($_)>.
=item fcntl FILEHANDLE,FUNCTION,SCALAR
Implements the fcntl(2) function. You'll probably have to say
use Fcntl;
first to get the correct constant definitions. Argument processing and
value return works just like C<ioctl()> below.
For example:
use Fcntl;
fcntl($filehandle, F_GETFL, $packed_return_buffer)
or die "can't fcntl F_GETFL: $!";
You don't have to check for C<defined()> on the return from
C<fnctl()>. Like C<ioctl()>, 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 on improper numeric
conversions.
Note that C<fcntl()> will produce a fatal error if used on a machine that
doesn't implement fcntl(2).
=item fileno FILEHANDLE
Returns the file descriptor for a filehandle. This is useful for
constructing bitmaps for C<select()> and low-level POSIX tty-handling
operations. If FILEHANDLE is an expression, the value is taken as
an indirect filehandle, generally its name.
You can use this to find out whether two handles refer to the
same underlying descriptor:
if (fileno(THIS) == fileno(THAT)) {
print "THIS and THAT are dups\n";
}
=item flock FILEHANDLE,OPERATION
Calls flock(2), or an emulation of it, on FILEHANDLE. Returns TRUE for
success, FALSE on failure. Produces a fatal error if used on a machine
that doesn't implement flock(2), fcntl(2) locking, or lockf(3). C<flock()>
is Perl's portable file locking interface, although it locks only entire
files, not records.
On many platforms (including most versions or clones of Unix), locks
established by C<flock()> are B<merely advisory>. Such discretionary locks
are more flexible, but offer fewer guarantees. This means that files
locked with C<flock()> may be modified by programs that do not also use
C<flock()>. Windows NT and OS/2 are among the platforms which
enforce mandatory locking. See your local documentation for details.
OPERATION is one of LOCK_SH, LOCK_EX, or LOCK_UN, possibly combined with
LOCK_NB. These constants are traditionally valued 1, 2, 8 and 4, but
you can use the symbolic names if import them from the Fcntl module,
either individually, or as a group using the ':flock' tag. LOCK_SH
requests a shared lock, LOCK_EX requests an exclusive lock, and LOCK_UN
releases a previously requested lock. If LOCK_NB is added to LOCK_SH or
LOCK_EX then C<flock()> will return immediately rather than blocking
waiting for the lock (check the return status to see if you got it).
To avoid the possibility of mis-coordination, Perl flushes FILEHANDLE
before (un)locking it.
Note that the emulation built with lockf(3) doesn't provide shared
locks, and it requires that FILEHANDLE be open with write intent. These
are the semantics that lockf(3) implements. Most (all?) systems
implement lockf(3) in terms of fcntl(2) locking, though, so the
differing semantics shouldn't bite too many people.
Note also that some versions of C<flock()> cannot lock things over the
network; you would need to use the more system-specific C<fcntl()> for
that. If you like you can force Perl to ignore your system's flock(2)
function, and so provide its own fcntl(2)-based emulation, by passing
the switch C<-Ud_flock> to the F<Configure> program when you configure
perl.
Here's a mailbox appender for BSD systems.
use Fcntl ':flock'; # import LOCK_* constants
sub lock {
flock(MBOX,LOCK_EX);
# and, in case someone appended
# while we were waiting...
seek(MBOX, 0, 2);
}
sub unlock {
flock(MBOX,LOCK_UN);
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?