perlfaq7.pod

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

POD
1,034
字号
=head1 NAMEperlfaq7 - General Perl Language Issues ($Revision: 10100 $)=head1 DESCRIPTIONThis section deals with general Perl language issues that don'tclearly fit into any of the other sections.=head2 Can I get a BNF/yacc/RE for the Perl language?There is no BNF, but you can paw your way through the yacc grammar inperly.y in the source distribution if you're particularly brave.  Thegrammar relies on very smart tokenizing code, so be prepared toventure into toke.c as well.In the words of Chaim Frenkel: "Perl's grammar can not be reduced to BNF.The work of parsing perl is distributed between yacc, the lexer, smokeand mirrors."=head2 What are all these $@%&* punctuation signs, and how do I know when to use them?They are type specifiers, as detailed in L<perldata>:	$ for scalar values (number, string or reference)	@ for arrays	% for hashes (associative arrays)	& for subroutines (aka functions, procedures, methods)	* for all types of that symbol name.  In version 4 you used them like	  pointers, but in modern perls you can just use references.There are couple of other symbols that you're likely to encounter that aren'treally type specifiers:	<> are used for inputting a record from a filehandle.	\  takes a reference to something.Note that <FILE> is I<neither> the type specifier for filesnor the name of the handle.  It is the C<< <> >> operator appliedto the handle FILE.  It reads one line (well, record--seeL<perlvar/$E<sol>>) from the handle FILE in scalar context, or I<all> linesin list context.  When performing open, close, or any other operationbesides C<< <> >> on files, or even when talking about the handle, doI<not> use the brackets.  These are correct: C<eof(FH)>, C<seek(FH, 0,2)> and "copying from STDIN to FILE".=head2 Do I always/never have to quote my strings or use semicolons and commas?Normally, a bareword doesn't need to be quoted, but in most casesprobably should be (and must be under C<use strict>).  But a hash keyconsisting of a simple word (that isn't the name of a definedsubroutine) and the left-hand operand to the C<< => >> operator bothcount as though they were quoted:	This                    is like this	------------            ---------------	$foo{line}              $foo{'line'}	bar => stuff            'bar' => stuffThe final semicolon in a block is optional, as is the final comma in alist.  Good style (see L<perlstyle>) says to put them in except forone-liners:	if ($whoops) { exit 1 }	@nums = (1, 2, 3);		if ($whoops) {		exit 1;	}	@lines = (	"There Beren came from mountains cold",	"And lost he wandered under leaves",	);=head2 How do I skip some return values?One way is to treat the return values as a list and index into it:	$dir = (getpwnam($user))[7];Another way is to use undef as an element on the left-hand-side:	($dev, $ino, undef, undef, $uid, $gid) = stat($file);You can also use a list slice to select only the elements thatyou need:	($dev, $ino, $uid, $gid) = ( stat($file) )[0,1,4,5];=head2 How do I temporarily block warnings?If you are running Perl 5.6.0 or better, the C<use warnings> pragmaallows fine control of what warning are produced.See L<perllexwarn> for more details.	{	no warnings;          # temporarily turn off warnings	$a = $b + $c;         # I know these might be undef	}Additionally, you can enable and disable categories of warnings.You turn off the categories you want to ignore and you can stillget other categories of warnings.  See L<perllexwarn> for thecomplete details, including the category names and hierarchy.	{	no warnings 'uninitialized';	$a = $b + $c;	}If you have an older version of Perl, the C<$^W> variable (documentedin L<perlvar>) controls runtime warnings for a block:	{	local $^W = 0;        # temporarily turn off warnings	$a = $b + $c;         # I know these might be undef	}Note that like all the punctuation variables, you cannot currentlyuse my() on C<$^W>, only local().=head2 What's an extension?An extension is a way of calling compiled C code from Perl.  ReadingL<perlxstut> is a good place to learn more about extensions.=head2 Why do Perl operators have different precedence than C operators?Actually, they don't.  All C operators that Perl copies have the sameprecedence in Perl as they do in C.  The problem is with operators that Cdoesn't have, especially functions that give a list context to everythingon their right, eg. print, chmod, exec, and so on.  Such functions arecalled "list operators" and appear as such in the precedence table inL<perlop>.A common mistake is to write:	unlink $file || die "snafu";This gets interpreted as:	unlink ($file || die "snafu");To avoid this problem, either put in extra parentheses or use thesuper low precedence C<or> operator:	(unlink $file) || die "snafu";	unlink $file or die "snafu";The "English" operators (C<and>, C<or>, C<xor>, and C<not>)deliberately have precedence lower than that of list operators forjust such situations as the one above.Another operator with surprising precedence is exponentiation.  Itbinds more tightly even than unary minus, making C<-2**2> product anegative not a positive four.  It is also right-associating, meaningthat C<2**3**2> is two raised to the ninth power, not eight squared.Although it has the same precedence as in C, Perl's C<?:> operatorproduces an lvalue.  This assigns $x to either $a or $b, dependingon the trueness of $maybe:	($maybe ? $a : $b) = $x;=head2 How do I declare/create a structure?In general, you don't "declare" a structure.  Just use a (probablyanonymous) hash reference.  See L<perlref> and L<perldsc> for details.Here's an example:	$person = {};                   # new anonymous hash	$person->{AGE}  = 24;           # set field AGE to 24	$person->{NAME} = "Nat";        # set field NAME to "Nat"	If you're looking for something a bit more rigorous, try L<perltoot>.=head2 How do I create a module?(contributed by brian d foy)L<perlmod>, L<perlmodlib>, L<perlmodstyle> explain modulesin all the gory details. L<perlnewmod> gives a briefoverview of the process along with a couple of suggestionsabout style.If you need to include C code or C library interfaces inyour module, you'll need h2xs.  h2xs will create the moduledistribution structure and the initial interface filesyou'll need.  L<perlxs> and L<perlxstut> explain the details.If you don't need to use C code, other tools such asExtUtils::ModuleMaker and Module::Starter, can help youcreate a skeleton module distribution.You may also want to see Sam Tregar's "Writing Perl Modulesfor CPAN" ( http://apress.com/book/bookDisplay.html?bID=14 )which is the best hands-on guide to creating moduledistributions.=head2 How do I adopt or take over a module already on CPAN?(contributed by brian d foy)The easiest way to take over a module is to have the currentmodule maintainer either make you a co-maintainer or transferthe module to you.If you can't reach the author for some reason (e.g. email bounces),the PAUSE admins at modules@perl.org can help. The PAUSE adminstreat each case individually.=over 4=itemGet a login for the Perl Authors Upload Server (PAUSE) if you don'talready have one: http://pause.perl.org=itemWrite to modules@perl.org explaining what you did to contact thecurrent maintainer. The PAUSE admins will also try to reach themaintainer.=item Post a public message in a heavily trafficked site announcing yourintention to take over the module.=itemWait a bit. The PAUSE admins don't want to act too quickly in casethe current maintainer is on holiday. If there's no response to private communication or the public post, a PAUSE admin can transferit to you.=back=head2 How do I create a class?See L<perltoot> for an introduction to classes and objects, as well asL<perlobj> and L<perlbot>.=head2 How can I tell if a variable is tainted?You can use the tainted() function of the Scalar::Util module, availablefrom CPAN (or included with Perl since release 5.8.0).See also L<perlsec/"Laundering and Detecting Tainted Data">.=head2 What's a closure?Closures are documented in L<perlref>.I<Closure> is a computer science term with a precise buthard-to-explain meaning. Usually, closures are implemented in Perl asanonymous subroutines with lasting references to lexical variablesoutside their own scopes. These lexicals magically refer to thevariables that were around when the subroutine was defined (deep binding).Closures are most often used in programming languages where you canhave the return value of a function be itself a function, as you canin Perl. Note that some languages provide anonymous functions but arenot capable of providing proper closures: the Python language, forexample.  For more information on closures, check out any textbook onfunctional programming.  Scheme is a language that not only supportsbut encourages closures.Here's a classic non-closure function-generating function:	sub add_function_generator {		return sub { shift() + shift() };		}	$add_sub = add_function_generator();	$sum = $add_sub->(4,5);                # $sum is 9 now.The anonymous subroutine returned by add_function_generator() isn'ttechnically a closure because it refers to no lexicals outside its ownscope.  Using a closure gives you a I<function template> with somecustomization slots left out to be filled later.Contrast this with the following make_adder() function, in which thereturned anonymous function contains a reference to a lexical variableoutside the scope of that function itself.  Such a reference requiresthat Perl return a proper closure, thus locking in for all time thevalue that the lexical had when the function was created.	sub make_adder {		my $addpiece = shift;		return sub { shift() + $addpiece };	}		$f1 = make_adder(20);	$f2 = make_adder(555);Now C<&$f1($n)> is always 20 plus whatever $n you pass in, whereasC<&$f2($n)> is always 555 plus whatever $n you pass in.  The $addpiecein the closure sticks around.Closures are often used for less esoteric purposes.  For example, whenyou want to pass in a bit of code into a function:	my $line;	timeout( 30, sub { $line = <STDIN> } );If the code to execute had been passed in as a string,C<< '$line = <STDIN>' >>, there would have been no way for thehypothetical timeout() function to access the lexical variable$line back in its caller's scope.Another use for a closure is to make a variable I<private> to anamed subroutine, e.g. a counter that gets initialized at creationtime of the sub and can only be modified from within the sub.This is sometimes used with a BEGIN block in package files to makesure a variable doesn't get meddled with during the lifetime of thepackage:	BEGIN {		my $id = 0;		sub next_id { ++$id }	}This is discussed in more detail in L<perlsub>, see the entry onI<Persistent Private Variables>.=head2 What is variable suicide and how can I prevent it?This problem was fixed in perl 5.004_05, so preventing it means upgradingyour version of perl. ;)Variable suicide is when you (temporarily or permanently) lose the valueof a variable.  It is caused by scoping through my() and local()interacting with either closures or aliased foreach() iterator variablesand subroutine arguments.  It used to be easy to inadvertently lose avariable's value this way, but now it's much harder.  Take this code:	my $f = 'foo';	sub T {		while ($i++ < 3) { my $f = $f; $f .= "bar"; print $f, "\n" }		}	T;	print "Finally $f\n";

⌨️ 快捷键说明

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