perlfaq7.pod
来自「视频监控网络部分的协议ddns,的模块的实现代码,请大家大胆指正.」· POD 代码 · 共 1,034 行 · 第 1/3 页
POD
1,034 行
If you are experiencing variable suicide, that C<my $f> in the subroutinedoesn't pick up a fresh copy of the C<$f> whose value is <foo>. The outputshows that inside the subroutine the value of C<$f> leaks through when itshouldn't, as in this output: foobar foobarbar foobarbarbar Finally fooThe $f that has "bar" added to it three times should be a new C<$f>C<my $f> should create a new lexical variable each time through the loop.The expected output is: foobar foobar foobar Finally foo=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", later in L<perlfaq7>, for information onpassing regular expressions.=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 FilehandlesAs of Perl 5.6, you can represent filehandles with scalar variableswhich you treat as any other scalar. open my $fh, $filename or die "Cannot open $filename! $!"; func( $fh ); sub func { my $passed_fh = shift; my $line = <$passed_fh>; }Before Perl 5.6, you had to 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.=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?(contributed by brian d foy)Perl doesn't have "static" variables, which can only be accessed fromthe function in which they are declared. You can get the same effectwith lexical variables, though.You can fake a static variable by using a lexical variable which goesout of scope. In this example, you define the subroutine C<counter>, andit uses the lexical variable C<$count>. Since you wrap this in a BEGINblock, C<$count> is defined at compile-time, but also goes out ofscope at the end of the BEGIN block. The BEGIN block also ensures thatthe subroutine and the value it uses is defined at compile-time so thesubroutine is ready to use just like any other subroutine, and you canput this code in the same place as other subroutines in the programtext (i.e. at the end of the code, typically). The subroutineC<counter> still has a reference to the data, and is the only way youcan access the value (and each time you do, you increment the value).The data in chunk of memory defined by C<$count> is private toC<counter>. BEGIN { my $count = 1; sub counter { $count++ } } my $start = counter(); .... # code that calls counter(); my $end = counter();In the previous example, you created a function-private variablebecause only one function remembered its reference. You could definemultiple functions while the variable is in scope, and each functioncan share the "private" variable. It's not really "static" because youcan access it outside the function while the lexical variable is inscope, and even create references to it. In this example,C<increment_count> and C<return_count> share the variable. Onefunction adds to the value and the other simply returns the value.They can both access C<$count>, and since it has gone out of scope,there is no other way to access it. BEGIN { my $count = 1; sub increment_count { $count++ } sub return_count { $count } }To declare a file-private variable, you still use a lexical variable.A file is also a scope, so a lexical variable defined in the filecannot be seen from any other file.See L<perlsub/"Persistent Private Variables"> for more information.The discussion of closures in L<perlref> may help you even though wedid not use anonymous subroutines in this answer. SeeL<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()"> andL<perlsub/"Temporary Values via local()"> for excruciating details.=head2 How can I access a dynamic variable while a similarly named lexical is in scope?If you know your package, you can just mention it explicitly, as in$Some_Pack::var. Note that the notation $::var is B<not> the dynamic $varin the current package, but rather the one in the "main" package, asthough you had written $main::var. use vars '$var'; local $var = "global"; my $var = "lexical"; print "lexical is $var\n"; print "global is $main::var\n";Alternatively you can use the compiler directive our() to bring adynamic variable into the current lexical scope. require 5.006; # our() did not exist before 5.6 use vars '$var'; local $var = "global"; my $var = "lexical"; print "lexical is $var\n"; { our $var; print "global is $var\n"; }=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) = E<lt>FILEE<gt>;" 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>),or via a forward reference or C<use subs> declaration. Even in thiscase, you get a clean @_ without any of the old values leaking throughwhere they don't belong.=head2 How do I create a switch or case statement?
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?