perlfunc.pod

来自「MSYS在windows下模拟了一个类unix的终端」· POD 代码 · 共 1,621 行 · 第 1/5 页

POD
1,621
字号
Note that, because C<eval> traps otherwise-fatal errors, it is useful fordetermining whether a particular feature (such as C<socket> or C<symlink>)is implemented.  It is also Perl's exception trapping mechanism, wherethe die operator is used to raise exceptions.If the code to be executed doesn't vary, you may use the eval-BLOCKform to trap run-time errors without incurring the penalty ofrecompiling 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 $@Due to the current arguably broken state of C<__DIE__> hooks, when usingthe C<eval{}> form as an exception trap in libraries, you may wish notto 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 callC<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"    }Because this promotes action at a distance, this counterintuitive behaviormay be fixed in a future release.With an C<eval>, you should be especially careful to remember what'sbeing 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 6Cases 1 and 2 above behave identically: they run the code contained inthe variable $x.  (Although case 2 has misleading double quotes makingthe reader wonder what else might be happening (nothing is).)  Cases 3and 4 likewise behave in the same way: they run the code C<'$x'>, whichdoes nothing but return the value of $x.  (Case 4 is preferred forpurely visual reasons, but it also has the advantage of compiling atcompile-time instead of at run-time.)  Case 5 is a place wherenormally you I<would> like to use double quotes, except that in thisparticular situation, you can just use symbolic references instead, asin case 6.C<eval BLOCK> does I<not> count as a loop, so the loop control statementsC<next>, C<last>, or C<redo> cannot be used to leave or restart the block.=item exec LIST=item exec PROGRAM LISTThe 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 andreturns false only if the command does not exist I<and> it is executeddirectly instead of via your system's command shell (see below).Since it's a common mistake to use C<exec> instead of C<system>, Perlwarns 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 youI<really> want to follow an C<exec> with some other statement, youcan 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 arraywith 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 intowords and passed directly to C<execvp>, which is more efficient.  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 lieto the program you are executing about its own name, you can specifythe program you actually want to run as an "indirect object" (without acomma) in front of the LIST.  (This always forces interpretation of theLIST as a multivalued list, even if there is only a single scalar inthe list.)  Example:    $shell = '/bin/csh';    exec $shell '-sh';		# pretend it's a login shellor, more directly,    exec {'/bin/csh'} '-sh';	# pretend it's a login shellWhen the arguments get executed via the system shell, results willbe subject to its quirks and capabilities.  See L<perlop/"`STRING`">for details.Using an indirect object with C<exec> or C<system> is also moresecure.  This usage (which also works fine with system()) forcesinterpretation of the arguments as a multivalued list, even if thelist had just one argument.  That way you're safe from the shellexpanding wildcards or splitting up words with whitespace in them.    @args = ( "echo surprise" );    exec @args;               # subject to shell escapes                                # if @args == 1    exec { $args[0] } @args;  # safe even with one-arg listThe first version, the one without the indirect object, ran the I<echo>program, passing it C<"surprise"> an argument.  The second versiondidn'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.Beginning with v5.6.0, Perl will attempt to flush all files opened foroutput before the exec, but this may not be supported on some platforms(see L<perlport>).  To be safe, you may need to set C<$|> ($AUTOFLUSHin English) or call the C<autoflush()> method of C<IO::Handle> on anyopen handles in order to avoid lost output.Note that C<exec> will not call your C<END> blocks, nor will it callany C<DESTROY> methods in your objects.=item exists EXPRGiven an expression that specifies a hash element or array element,returns true if the specified element in the hash or array has everbeen initialized, even if the corresponding value is undefined.  Theelement is not autovivified if it doesn't exist.    print "Exists\n" 	if exists $hash{$key};    print "Defined\n" 	if defined $hash{$key};    print "True\n"      if $hash{$key};    print "Exists\n" 	if exists $array[$index];    print "Defined\n" 	if defined $array[$index];    print "True\n"      if $array[$index];A hash or array element can be true only if it's defined, and defined ifit exists, but the reverse doesn't necessarily hold true.Given an expression that specifies the name of a subroutine,returns true if the specified subroutine has ever been declared, evenif it is undefined.  Mentioning a subroutine name for exists or defineddoes not count as declaring it.  Note that a subroutine which does notexist may still be callable: its package may have an C<AUTOLOAD>method that makes it spring into existence the first time that it iscalled -- see L<perlsub>.    print "Exists\n" 	if exists &subroutine;    print "Defined\n" 	if defined &subroutine;Note that the EXPR can be arbitrarily complicated as long as the finaloperation is a hash or array key lookup or subroutine name:    if (exists $ref->{A}->{B}->{$key}) 	{ }    if (exists $hash{A}{B}{$key}) 	{ }    if (exists $ref->{A}->{B}->[$ix]) 	{ }    if (exists $hash{A}{B}[$ix]) 	{ }    if (exists &{$ref->{A}{B}{$key}})   { }Although the deepest nested array or hash will not spring into existencejust because its existence was tested, any intervening ones will.Thus C<< $ref->{"A"} >> and C<< $ref->{"A"}->{"B"} >> will springinto existence due to the existence test for the $key element above.This happens anywhere the arrow operator is used, including even:    undef $ref;    if (exists $ref->{"Some key"})	{ }    print $ref; 	    # prints HASH(0x80d3d5c)This surprising autovivification in what does not at first--or evensecond--glance appear to be an lvalue context may be fixed in a futurerelease.See L<perlref/"Pseudo-hashes: Using an array as a hash"> for specificson how exists() acts when used on a pseudo-hash.Use of a subroutine call, rather than a subroutine name, as an argumentto exists() is an error.    exists &sub;	# OK    exists &sub();	# Error=item exit EXPREvaluates EXPR and exits immediately with that value.    Example:    $ans = <STDIN>;    exit 0 if $ans =~ /^[Xx]/;See also C<die>.  If EXPR is omitted, exits with C<0> status.  The onlyuniversally recognized values for EXPR are C<0> for success and C<1>for error; other values are subject to interpretation depending on theenvironment in which the Perl program is running.  For example, exiting69 (EX_UNAVAILABLE) from a I<sendmail> incoming-mail filter will causethe mailer to return the item undelivered, but that's not true everywhere.Don't use C<exit> to abort a subroutine if there's any chance thatsomeone might want to trap whatever error happened.  Use C<die> instead,which can be trapped by an C<eval>.The exit() function does not always exit immediately.  It calls anydefined C<END> routines first, but these C<END> routines may notthemselves abort the exit.  Likewise any object destructors that need tobe called are called before the real exit.  If this is a problem, youcan call C<POSIX:_exit($status)> to avoid END and destructor processing.See L<perlmod> for details.=item exp EXPR=item expReturns I<e> (the natural logarithm base) to the power of EXPR.  If EXPR is omitted, gives C<exp($_)>.=item fcntl FILEHANDLE,FUNCTION,SCALARImplements the fcntl(2) function.  You'll probably have to say    use Fcntl;first to get the correct constant definitions.  Argument processing andvalue 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 intoC<"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> warningson improper numeric conversions.Note that C<fcntl> will produce a fatal error if used on a machine thatdoesn't implement fcntl(2).  See the Fcntl module or your fcntl(2)manpage to learn what functions are available on your system.=item fileno FILEHANDLEReturns the file descriptor for a filehandle, or undefined if thefilehandle is not open.  This is mainly useful for constructingbitmaps for C<select> and low-level POSIX tty-handling operations.If FILEHANDLE is an expression, the value is taken as an indirectfilehandle, 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,OPERATIONCalls flock(2), or an emulation of it, on FILEHANDLE.  Returns truefor success, false on failure.  Produces a fatal error if used on amachine that doesn't implement flock(2), fcntl(2) locking, or lockf(3).C<flock> is Perl's portable file locking interface, although it locksonly entire files, not records.Two potentially non-obvious but traditional C<flock> semantics arethat it waits indefinitely until the lock is granted, and that its locksB<merely advisory>.  Such discretionary locks are more flexible, but offerfewer guarantees.  This means that files locked with C<flock> may bemodified by programs that do not also use C<flock>.  See L<perlport>,your port's specific documentation, or your system-specific local manpagesfor details.  It's best to assume traditional behavior if you're writingportable programs.  (But if you're not, you should as always feel perfectlyfree to write for your own system's idiosyncrasies (sometimes called"features").  Slavish adherence to portability concerns shouldn't getin the way of your getting your job done.)OPERATION is one of LOCK_SH, LOCK_EX, or LOCK_UN, possibly combined withLOCK_NB.  These constants are traditionally valued 1, 2, 8 and 4, butyou can use the symbolic names if you import them from the Fcntl module,either individually, or as a group using the ':flock' tag.  LOCK_SHrequests a shared lock, LOCK_EX requests an exclusive lock, and LOCK_UNreleases a previously requested lock.  If LOCK_NB is bitwise-or'ed withLOCK_SH or LOCK_EX then C<flock> will return immediately rather than blockingwaiting for the lock (check the return status to see if you got it).To avoid the possibility of miscoordination, Perl now flushes FILEHANDLEbefore locking or unlocking it.Note that the emulation built with lockf(3) doesn't provide sharedlocks, and it requires that FILEHANDLE be open with write intent.  Theseare the semantics that lockf(3) implements.  Most if not all systemsimplement lockf(3) in terms of fcntl(2) locking, though, so thediffering semantics shouldn't bite too many people.Note also that some versions of C<flock> cannot loc

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?