perlfunc.pod

来自「视频监控网络部分的协议ddns,的模块的实现代码,请大家大胆指正.」· POD 代码 · 共 1,629 行 · 第 1/5 页

POD
1,629
字号
        }        else {            # handle all other possible exceptions        }    }Because perl will stringify uncaught exception messages before displayingthem, you may want to overload stringification operations on such customexception objects.  See L<overload> for details about that.You can arrange for a callback to be run just before the C<die>does its deed, by setting the C<$SIG{__DIE__}> hook.  The associatedhandler will be called with the error text and can change the errormessage, if it sees fit, by calling C<die> again.  SeeL<perlvar/$SIG{expr}> for details on setting C<%SIG> entries, andL<"eval BLOCK"> for some examples.  Although this feature was to be run only right before your program was to exit, this is notcurrently the case--the C<$SIG{__DIE__}> hook is currently calledeven inside eval()ed blocks/strings!  If one wants the hook to donothing in such situations, put	die @_ if $^S;as the first line of the handler (see L<perlvar/$^S>).  Becausethis promotes strange action at a distance, this counterintuitivebehavior may be fixed in a future release.=item do BLOCKX<do> X<block>Not really a function.  Returns the value of the last command in thesequence of commands indicated by BLOCK.  When modified by the C<while> orC<until> loop modifier, executes the BLOCK once before testing the loopcondition. (On other statements the loop modifiers test the conditionalfirst.)C<do 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.See L<perlsyn> for alternative strategies.=item do SUBROUTINE(LIST)X<do>This form of subroutine call is deprecated.  See L<perlsub>.=item do EXPRX<do>Uses the value of EXPR as a filename and executes the contents of thefile as a Perl script.    do 'stat.pl';is just like    eval `cat stat.pl`;except that it's more efficient and concise, keeps track of the currentfilename for error messages, searches the @INC directories, and updatesC<%INC> if the file is found.  See L<perlvar/Predefined Names> for thesevariables.  It also differs in that code evaluated with C<do FILENAME>cannot see lexicals in the enclosing scope; C<eval STRING> does.  It's thesame, however, in that it does reparse the file every time you call it,so you probably don't want to do this inside a loop.If C<do> cannot read the file, it returns undef and sets C<$!> to theerror.  If C<do> can read the file but cannot compile it, itreturns undef and sets an error message in C<$@>.   If the file issuccessfully compiled, C<do> returns the value of the last expressionevaluated.Note that inclusion of library modules is better done with theC<use> and C<require> operators, which also do automatic error checkingand raise an exception if there's a problem.You might like to use C<do> to read in a program configurationfile.  Manual error checking can be done this way:    # read in config files: system first, then user    for $file ("/share/prog/defaults.rc",               "$ENV{HOME}/.someprogrc")   {	unless ($return = do $file) {	    warn "couldn't parse $file: $@" if $@;	    warn "couldn't do $file: $!"    unless defined $return;	    warn "couldn't run $file"       unless $return;	}    }=item dump LABELX<dump> X<core> X<undump>=item dumpThis function causes an immediate core dump.  See also the B<-u>command-line switch in L<perlrun>, which does the same thing.Primarily this is so that you can use the B<undump> program (notsupplied) to turn your core dump into an executable binary afterhaving initialized all your variables at the beginning of theprogram.  When the new binary is executed it will begin by executinga C<goto LABEL> (with all the restrictions that C<goto> suffers).Think of it as a goto with an intervening core dump and reincarnation.If C<LABEL> is omitted, restarts the program from the top.B<WARNING>: Any files opened at the time of the dump will I<not>be open any more when the program is reincarnated, with possibleresulting confusion on the part of Perl.This function is now largely obsolete, mostly because it's very hard toconvert a core file into an executable. That's why you should now invokeit as C<CORE::dump()>, if you don't want to be warned against a possibletypo.=item each HASHX<each> X<hash, iterator>When called in list context, returns a 2-element list consisting of thekey and value for the next element of a hash, so that you can iterate overit.  When called in scalar context, returns only the key for the nextelement in the hash.Entries are returned in an apparently random order.  The actual randomorder is subject to change in future versions of perl, but it isguaranteed to be in the same order as either the C<keys> or C<values>function would produce on the same (unmodified) hash.  Since Perl5.8.1 the ordering is different even between different runs of Perlfor security reasons (see L<perlsec/"Algorithmic Complexity Attacks">).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<undef> inscalar context.  The next call to C<each> after that will start iteratingagain.  There is a single iterator for each hash, shared by all C<each>,C<keys>, and C<values> function calls in the program; it can be reset byreading all the elements from the hash, or by evaluating C<keys HASH> orC<values HASH>.  If you add or delete elements of a hash while you'reiterating over it, you may get entries skipped or duplicated, sodon't.  Exception: It is always safe to delete the item most recentlyreturned by C<each()>, which means that the following code will work:        while (($key, $value) = each %hash) {          print $key, "\n";          delete $hash{$key};   # This is safe        }The following prints out your environment like the printenv(1) program,only in a different order:    while (($key,$value) = each %ENV) {	print "$key=$value\n";    }See also C<keys>, C<values> and C<sort>.=item eof FILEHANDLEX<eof>X<end of file>X<end-of-file>=item eof ()=item eofReturns 1 if the next read on FILEHANDLE will return end of file, or ifFILEHANDLE is not open.  FILEHANDLE may be an expression whose valuegives the real filehandle.  (Note that this function actuallyreads a character and then C<ungetc>s it, so isn't very useful in aninteractive context.)  Do not read from a terminal file (or callC<eof(FILEHANDLE)> on it) after end-of-file is reached.  File types suchas terminals may lose the end-of-file condition if you do.An C<eof> without an argument uses the last file read.  Using C<eof()>with empty parentheses is very different.  It refers to the pseudo fileformed from the files listed on the command line and accessed via theC<< <> >> operator.  Since C<< <> >> isn't explicitly opened,as a normal filehandle is, an C<eof()> before C<< <> >> has beenused will cause C<@ARGV> to be examined to determine if input isavailable.   Similarly, an C<eof()> after C<< <> >> has returnedend-of-file will assume you are processing another C<@ARGV> list,and if you haven't set C<@ARGV>, will read input from C<STDIN>;see L<perlop/"I/O Operators">.In a C<< while (<>) >> loop, C<eof> or C<eof(ARGV)> can be used todetect the end of each file, C<eof()> will only detect the end of thelast file.  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 last file	    print "--------------\n";	}	print;	last if eof();          # needed if we're reading from a terminal    }Practical hint: you almost never need to use C<eof> in Perl, because theinput operators typically return C<undef> when they run out of data, or ifthere was an error.=item eval EXPRX<eval> X<try> X<catch> X<evaluate> X<parse> X<execute>X<error, handling> X<exception, handling>=item eval BLOCK=item evalIn the first form, the return value of EXPR is parsed and executed as if itwere a little Perl program.  The value of the expression (which is itselfdetermined within scalar context) is first parsed, and if there weren't anyerrors, executed in the lexical context of the current Perl program, sothat any variable settings or subroutine and format definitions remainafterwards.  Note that the value is parsed every time the C<eval> executes.If EXPR is omitted, evaluates C<$_>.  This form is typically used todelay 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 thesame time the code surrounding the C<eval> itself was parsed--and executedwithin the context of the current Perl program.  This form is typicallyused to trap exceptions more efficiently than the first (see below), whilealso providing the benefit of checking the code within BLOCK at compiletime.The final semicolon, if any, may be omitted from the value of EXPR or withinthe BLOCK.In both forms, the value returned is the value of the last expressionevaluated inside the mini-program; a return statement may be also used, justas with subroutines.  The expression providing the return value is evaluatedin void, scalar, or list context, depending on the context of the C<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 isexecuted, an undefined value is returned by C<eval>, and C<$@> is set to theerror message.  If there was no error, C<$@> is guaranteed to be a nullstring.  Beware that using C<eval> neither silences perl from printingwarnings 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, orturn off warnings inside the BLOCK or EXPR using S<C<no warnings 'all'>>.See L</warn>, L<perlvar>, L<warnings> and L<perllexwarn>.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 $@Using the C<eval{}> form as an exception trap in libraries does have someissues.  Due to the current arguably broken state of C<__DIE__> hooks, youmay 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 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.Note that as a very special case, an C<eval ''> executed within the C<DB>package doesn't see the usual surrounding lexical scope, but rather thescope of the first non-DB piece of code that called it. You don't normallyneed to worry about this unless you are writing a Perl 

⌨️ 快捷键说明

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