perlfunc.pod

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

POD
1,621
字号
	delete $HASH{$key};    }    foreach $index (0 .. $#ARRAY) {	delete $ARRAY[$index];    }And so do these:    delete @HASH{keys %HASH};    delete @ARRAY[0 .. $#ARRAY];But both of these are slower than just assigning the empty listor undefining %HASH or @ARRAY:    %HASH = ();		# completely empty %HASH    undef %HASH;	# forget %HASH ever existed    @ARRAY = ();	# completely empty @ARRAY    undef @ARRAY;	# forget @ARRAY ever existedNote that the EXPR can be arbitrarily complicated as long as the finaloperation is a hash element, array element,  hash slice, or array slicelookup:    delete $ref->[$x][$y]{$key};    delete @{$ref->[$x][$y]}{$key1, $key2, @morekeys};    delete $ref->[$x][$y][$index];    delete @{$ref->[$x][$y]}[$index1, $index2, @moreindices];=item die LISTOutside an C<eval>, prints the value of LIST to C<STDERR> andexits with the current value of C<$!> (errno).  If C<$!> is C<0>,exits with the value of C<<< ($? >> 8) >>> (backtick `command`status).  If C<<< ($? >> 8) >>> is C<0>, exits with C<255>.  Insidean C<eval(),> the error message is stuffed into C<$@> and theC<eval> is terminated with the undefined value.  This makesC<die> the way to raise an exception.Equivalent examples:    die "Can't cd to spool: $!\n" unless chdir '/usr/spool/news';    chdir '/usr/spool/news' or die "Can't cd to spool: $!\n"If the value of EXPR does not end in a newline, the current script linenumber and input line number (if any) are also printed, and a newlineis supplied.  Note that the "input line number" (also known as "chunk")is subject to whatever notion of "line" happens to be currently ineffect, and is also available as the special variable C<$.>.See L<perlvar/"$/"> and L<perlvar/"$.">.Hint: sometimes appending C<", stopped"> to your messagewill cause it to make better sense when the string C<"at foo line 123"> isappended.  Suppose you are running script "canasta".    die "/etc/games is no good";    die "/etc/games is no good, stopped";produce, respectively    /etc/games is no good at canasta line 123.    /etc/games is no good, stopped at canasta line 123.See also exit(), warn(), and the Carp module.If LIST is empty and C<$@> already contains a value (typically from aprevious eval) that value is reused after appending C<"\t...propagated">.This is useful for propagating exceptions:    eval { ... };    die unless $@ =~ /Expected exception/;If C<$@> is empty then the string C<"Died"> is used.die() can also be called with a reference argument.  If this happens to betrapped within an eval(), $@ contains the reference.  This behavior permitsa more elaborate exception handling implementation using objects thatmaintain arbitrary state about the nature of the exception.  Such a schemeis sometimes preferable to matching particular string values of $@ usingregular expressions.  Here's an example:    eval { ... ; die Some::Module::Exception->new( FOO => "bar" ) };    if ($@) {        if (ref($@) && UNIVERSAL::isa($@,"Some::Module::Exception")) {            # handle Some::Module::Exception        }        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 meantto 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 BLOCKNot really a function.  Returns the value of the last command in thesequence of commands indicated by BLOCK.  When modified by a loopmodifier, executes the BLOCK once before testing the loop condition.(On other statements the loop modifiers test the conditional first.)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)A deprecated form of subroutine call.  See L<perlsub>.=item do EXPRUses the value of EXPR as a filename and executes the contents of thefile as a Perl script.  Its primary use is to include subroutinesfrom a Perl subroutine library.    do 'stat.pl';is just like    scalar eval `cat stat.pl`;except that it's more efficient and concise, keeps track of the currentfilename for error messages, searches the @INC libraries, 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 LABEL=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, partly because it's veryhard to convert a core file into an executable, and because thereal compiler backends for generating portable bytecode and compilableC code have superseded it.If you're looking to use L<dump> to speed up your program, considergenerating bytecode or native C code as described in L<perlcc>.  Ifyou're just trying to accelerate a CGI script, consider using theC<mod_perl> extension to B<Apache>, or the CPAN module, Fast::CGI.You might also consider autoloading or selfloading, which at leastmake your program I<appear> to run faster.  =item each HASHWhen 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 is guaranteedto be in the same order as either the C<keys> or C<values> functionwould produce on the same (unmodified) hash.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 FILEHANDLE=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.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 current file	    print "--------------\n";	    close(ARGV);	# close or last; is needed if we				# are reading from the terminal	}	print;    }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 EXPR=item eval BLOCKIn 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 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 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 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.  SeeL</warn> and L<perlvar>.

⌨️ 快捷键说明

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