perlfaq7.pod
来自「MSYS在windows下模拟了一个类unix的终端」· POD 代码 · 共 975 行 · 第 1/3 页
POD
975 行
Variable suicide is when you (temporarily or permanently) lose thevalue of a variable. It is caused by scoping through my() and local()interacting with either closures or aliased foreach() iteratorvariables and subroutine arguments. It used to be easy toinadvertently lose a variable's value this way, but now it's muchharder. Take this code: my $f = "foo"; sub T { while ($i++ < 3) { my $f = $f; $f .= "bar"; print $f, "\n" } } T; print "Finally $f\n";The $f that has "bar" added to it three times should be a new C<$f>(C<my $f> should create a new local variable each time through the loop).It isn't, however. This was a bug, now fixed in the latest releases(tested against 5.004_05, 5.005_03, and 5.005_56).=head2 How can I pass/return a {Function, FileHandle, Array, Hash, Method, Regex}?With the exception of regexes, you need to pass references to theseobjects. See L<perlsub/"Pass by Reference"> for this particularquestion, and L<perlref> for information on references.See ``Passing Regexes'', below, for information on passing regularexpressions.=over 4=item Passing Variables and FunctionsRegular variables and functions are quite easy to pass: just pass in areference to an existing or anonymous variable or function: func( \$some_scalar ); func( \@some_array ); func( [ 1 .. 10 ] ); func( \%some_hash ); func( { this => 10, that => 20 } ); func( \&some_func ); func( sub { $_[0] ** $_[1] } );=item Passing FilehandlesTo pass filehandles to subroutines, use the C<*FH> or C<\*FH> notations.These are "typeglobs"--see L<perldata/"Typeglobs and Filehandles">and especially L<perlsub/"Pass by Reference"> for more information.Here's an excerpt:If you're passing around filehandles, you could usually just use the baretypeglob, like *STDOUT, but typeglobs references would be better becausethey'll still work properly under C<use strict 'refs'>. For example: splutter(\*STDOUT); sub splutter { my $fh = shift; print $fh "her um well a hmmm\n"; } $rec = get_rec(\*STDIN); sub get_rec { my $fh = shift; return scalar <$fh>; }If you're planning on generating new filehandles, you could do this: sub openit { my $path = shift; local *FH; return open (FH, $path) ? *FH : undef; } $fh = openit('< /etc/motd'); print <$fh>;=item Passing RegexesTo pass regexes around, you'll need to be using a release of Perlsufficiently recent as to support the C<qr//> construct, pass aroundstrings and use an exception-trapping eval, or else be very, very clever.Here's an example of how to pass in a string to be regex comparedusing C<qr//>: sub compare($$) { my ($val1, $regex) = @_; my $retval = $val1 =~ /$regex/; return $retval; } $match = compare("old McDonald", qr/d.*D/i);Notice how C<qr//> allows flags at the end. That pattern was compiledat compile time, although it was executed later. The nifty C<qr//>notation wasn't introduced until the 5.005 release. Before that, youhad to approach this problem much less intuitively. For example, hereit is again if you don't have C<qr//>: sub compare($$) { my ($val1, $regex) = @_; my $retval = eval { $val1 =~ /$regex/ }; die if $@; return $retval; } $match = compare("old McDonald", q/($?i)d.*D/);Make sure you never say something like this: return eval "\$val =~ /$regex/"; # WRONGor someone can sneak shell escapes into the regex due to the doubleinterpolation of the eval and the double-quoted string. For example: $pattern_of_evil = 'danger ${ system("rm -rf * &") } danger'; eval "\$string =~ /$pattern_of_evil/";Those preferring to be very, very clever might see the O'Reilly book,I<Mastering Regular Expressions>, by Jeffrey Friedl. Page 273'sBuild_MatchMany_Function() is particularly interesting. A completecitation of this book is given in L<perlfaq2>.=item Passing MethodsTo pass an object method into a subroutine, you can do this: call_a_lot(10, $some_obj, "methname") sub call_a_lot { my ($count, $widget, $trick) = @_; for (my $i = 0; $i < $count; $i++) { $widget->$trick(); } }Or, you can use a closure to bundle up the object, itsmethod call, and arguments: my $whatnot = sub { $some_obj->obfuscate(@args) }; func($whatnot); sub func { my $code = shift; &$code(); }You could also investigate the can() method in the UNIVERSAL class(part of the standard perl distribution).=back=head2 How do I create a static variable?As with most things in Perl, TMTOWTDI. What is a "static variable" inother languages could be either a function-private variable (visibleonly within a single function, retaining its value between calls tothat function), or a file-private variable (visible only to functionswithin the file it was declared in) in Perl.Here's code to implement a function-private variable: BEGIN { my $counter = 42; sub prev_counter { return --$counter } sub next_counter { return $counter++ } }Now prev_counter() and next_counter() share a private variable $counterthat was initialized at compile time.To declare a file-private variable, you'll still use a my(), puttingthe declaration at the outer scope level at the top of the file.Assume this is in file Pax.pm: package Pax; my $started = scalar(localtime(time())); sub begun { return $started }When C<use Pax> or C<require Pax> loads this module, the variable willbe initialized. It won't get garbage-collected the way most variablesgoing out of scope do, because the begun() function cares about it,but no one else can get it. It is not called $Pax::started becauseits scope is unrelated to the package. It's scoped to the file. Youcould conceivably have several packages in that same file allaccessing the same private variable, but another file with the samepackage couldn't get to it.See L<perlsub/"Persistent Private Variables"> for details.=head2 What's the difference between dynamic and lexical (static) scoping? Between local() and my()?C<local($x)> saves away the old value of the global variable C<$x>and assigns a new value for the duration of the subroutine I<which isvisible in other functions called from that subroutine>. This is doneat run-time, so is called dynamic scoping. local() always affects globalvariables, also called package variables or dynamic variables.C<my($x)> creates a new variable that is only visible in the currentsubroutine. This is done at compile-time, so it is called lexical orstatic scoping. my() always affects private variables, also calledlexical variables or (improperly) static(ly scoped) variables.For instance: sub visible { print "var has value $var\n"; } sub dynamic { local $var = 'local'; # new temporary value for the still-global visible(); # variable called $var } sub lexical { my $var = 'private'; # new private variable, $var visible(); # (invisible outside of sub scope) } $var = 'global'; visible(); # prints global dynamic(); # prints local lexical(); # prints globalNotice how at no point does the value "private" get printed. That'sbecause $var only has that value within the block of the lexical()function, and it is hidden from called subroutine.In summary, local() doesn't make what you think of as private, localvariables. It gives a global variable a temporary value. my() iswhat you're looking for if you want private variables.See L<perlsub/"Private Variables via my()"> and L<perlsub/"Temporary Values via local()"> for excruciating details.=head2 How can I access a dynamic variable while a similarly named lexical is in scope?You can do this via symbolic references, provided you haven't setC<use strict "refs">. So instead of $var, use C<${'var'}>. local $var = "global"; my $var = "lexical"; print "lexical is $var\n"; no strict 'refs'; print "global is ${'var'}\n";If you know your package, you can just mention it explicitly, as in$Some_Pack::var. Note that the notation $::var is I<not> the dynamic$var in the current package, but rather the one in the C<main>package, as though you had written $main::var. Specifying the packagedirectly makes you hard-code its name, but it executes faster andavoids running afoul of C<use strict "refs">.=head2 What's the difference between deep and shallow binding?In deep binding, lexical variables mentioned in anonymous subroutinesare the same ones that were in scope when the subroutine was created.In shallow binding, they are whichever variables with the same nameshappen to be in scope when the subroutine is called. Perl always usesdeep binding of lexical variables (i.e., those created with my()).However, dynamic variables (aka global, local, or package variables)are effectively shallowly bound. Consider this just one more reasonnot to use them. See the answer to L<"What's a closure?">.=head2 Why doesn't "my($foo) = <FILE>;" work right?C<my()> and C<local()> give list context to the right hand sideof C<=>. The <FH> read operation, like so many of Perl'sfunctions and operators, can tell which context it was called in andbehaves appropriately. In general, the scalar() function can help.This function does nothing to the data itself (contrary to popular myth)but rather tells its argument to behave in whatever its scalar fashion is.If that function doesn't have a defined scalar behavior, this of coursedoesn't help you (such as with sort()).To enforce scalar context in this particular case, however, you needmerely omit the parentheses: local($foo) = <FILE>; # WRONG local($foo) = scalar(<FILE>); # ok local $foo = <FILE>; # rightYou should probably be using lexical variables anyway, although theissue is the same here: my($foo) = <FILE>; # WRONG my $foo = <FILE>; # right=head2 How do I redefine a builtin function, operator, or method?Why do you want to do that? :-)If you want to override a predefined function, such as open(),then you'll have to import the new definition from a differentmodule. See L<perlsub/"Overriding Built-in Functions">. There'salso an example in L<perltoot/"Class::Template">.If you want to overload a Perl operator, such as C<+> or C<**>,then you'll want to use the C<use overload> pragma, documentedin L<overload>.If you're talking about obscuring method calls in parent classes,see L<perltoot/"Overridden Methods">.=head2 What's the difference between calling a function as &foo and foo()?When you call a function as C<&foo>, you allow that function access toyour current @_ values, and you bypass prototypes.The function doesn't get an empty @_--it gets yours! While notstrictly speaking a bug (it's documented that way in L<perlsub>), itwould be hard to consider this a feature in most cases.When you call your function as C<&foo()>, then you I<do> get a new @_,but prototyping is still circumvented.Normally, you want to call a function using C<foo()>. You may onlyomit the parentheses if the function is already known to the compilerbecause it already saw the definition (C<use> but not C<require>),
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?