perlfaq7.pod

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

POD
975
字号
=head1 NAMEperlfaq7 - Perl Language Issues ($Revision: 1.28 $, $Date: 1999/05/23 20:36:18 $)=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/$/>) 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);=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    }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?A module is a package that lives in a file of the same name.  Forexample, the Hello::There module would live in Hello/There.pm.  Fordetails, read L<perlmod>.  You'll also find L<Exporter> helpful.  Ifyou're writing a C or mixed-language module with both C and Perl, thenyou should study L<perlxstut>.Here's a convenient template you might wish you use when starting yourown module.  Make sure to change the names appropriately.    package Some::Module;  # assumes Some/Module.pm    use strict;    use warnings;    BEGIN {	use Exporter   ();	our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);	## set the version for version checking; uncomment to use	## $VERSION     = 1.00;	# if using RCS/CVS, this next line may be preferred,	# but beware two-digit versions.	$VERSION = do{my@r=q$Revision: 1.28 $=~/\d+/g;sprintf '%d.'.'%02d'x$#r,@r};	@ISA         = qw(Exporter);	@EXPORT      = qw(&func1 &func2 &func3);	%EXPORT_TAGS = ( );  	# eg: TAG => [ qw!name1 name2! ],	# your exported package globals go here,	# as well as any optionally exported functions	@EXPORT_OK   = qw($Var1 %Hashit);    }    our @EXPORT_OK;    # exported package globals go here    our $Var1;    our %Hashit;    # non-exported package globals go here    our @more;    our $stuff;    # initialize package globals, first exported ones    $Var1   = '';    %Hashit = ();    # then the others (which are still accessible as $Some::Module::stuff)    $stuff  = '';    @more   = ();    # all file-scoped lexicals must be created before    # the functions below that use them.    # file-private lexicals go here    my $priv_var    = '';    my %secret_hash = ();    # here's a file-private function as a closure,    # callable as &$priv_func;  it cannot be prototyped.    my $priv_func = sub {        # stuff goes here.    };    # make all your functions, whether exported or not;    # remember to put something interesting in the {} stubs    sub func1      {}	 # no prototype    sub func2()    {}	 # proto'd void    sub func3($$)  {}	 # proto'd to 2 scalars    # this one isn't exported, but could be called!    sub func4(\%)  {}    # proto'd to 1 hash ref    END { }       # module clean-up code here (global destructor)    1;            # modules must return trueThe h2xs program will create stubs for all the important stuff for you:  % h2xs -XA -n My::Module=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?See L<perlsec/"Laundering and Detecting Tainted Data">.  Here's anexample (which doesn't use any system calls, because the kill()is given no processes to signal):    sub is_tainted {	return ! eval { join('',@_), kill 0; 1; };    }This is not C<-w> clean, however.  There is no C<-w> clean way todetect taintedness--take this as a hint that you should untaintall possibly-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. Closures are implemented in Perl as anonymoussubroutines with lasting references to lexical variables outside theirown scopes.  These lexicals magically refer to the variables that werearound when the subroutine was defined (deep binding).Closures make sense in any programming language where you can have thereturn value of a function be itself a function, as you can in Perl.Note that some languages provide anonymous functions but are notcapable 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 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 closure works as a I<function template> with some customizationslots left out to be filled later.  The anonymous subroutine returnedby add_function_generator() isn't technically a closure because itrefers to no lexicals outside its own scope.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.=head2 What is variable suicide and how can I prevent it?

⌨️ 快捷键说明

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