📄 perlsub.1
字号:
\& if ($@) {\& local $_ = $@;\& &$catch;\& }\& }\& sub catch (&) { $_[0] }\&\& try {\& die "phooey";\& } catch {\& /phooey/ and print "unphooey\en";\& };.Ve.PPThat prints \f(CW"unphooey"\fR. (Yes, there are still unresolvedissues having to do with visibility of \f(CW@_\fR. I'm ignoring thatquestion for the moment. (But note that if we make \f(CW@_\fR lexicallyscoped, those anonymous subroutines can act like closures... (Gee,is this sounding a little Lispish? (Never mind.)))).PPAnd here's a reimplementation of the Perl \f(CW\*(C`grep\*(C'\fR operator:.IX Xref "grep".PP.Vb 8\& sub mygrep (&@) {\& my $code = shift;\& my @result;\& foreach $_ (@_) {\& push(@result, $_) if &$code;\& }\& @result;\& }.Ve.PPSome folks would prefer full alphanumeric prototypes. Alphanumerics havebeen intentionally left out of prototypes for the express purpose ofsomeday in the future adding named, formal parameters. The currentmechanism's main goal is to let module writers provide better diagnosticsfor module users. Larry feels the notation quite understandable to Perlprogrammers, and that it will not intrude greatly upon the meat of themodule, nor make it harder to read. The line noise is visuallyencapsulated into a small pill that's easy to swallow..PPIf you try to use an alphanumeric sequence in a prototype you willgenerate an optional warning \- \*(L"Illegal character in prototype...\*(R".Unfortunately earlier versions of Perl allowed the prototype to beused as long as its prefix was a valid prototype. The warning may beupgraded to a fatal error in a future version of Perl once themajority of offending code is fixed..PPIt's probably best to prototype new functions, not retrofit prototypinginto older ones. That's because you must be especially careful aboutsilent impositions of differing list versus scalar contexts. For example,if you decide that a function should take just one parameter, like this:.PP.Vb 4\& sub func ($) {\& my $n = shift;\& print "you gave me $n\en";\& }.Ve.PPand someone has been calling it with an array or expressionreturning a list:.PP.Vb 2\& func(@foo);\& func( split /:/ );.Ve.PPThen you've just supplied an automatic \f(CW\*(C`scalar\*(C'\fR in front of theirargument, which can be more than a bit surprising. The old \f(CW@foo\fRwhich used to hold one thing doesn't get passed in. Instead,\&\f(CW\*(C`func()\*(C'\fR now gets passed in a \f(CW1\fR; that is, the number of elementsin \f(CW@foo\fR. And the \f(CW\*(C`split\*(C'\fR gets called in scalar context so itstarts scribbling on your \f(CW@_\fR parameter list. Ouch!.PPThis is all very powerful, of course, and should be used only in moderationto make the world a better place..Sh "Constant Functions".IX Xref "constant".IX Subsection "Constant Functions"Functions with a prototype of \f(CW\*(C`()\*(C'\fR are potential candidates forinlining. If the result after optimization and constant foldingis either a constant or a lexically-scoped scalar which has no otherreferences, then it will be used in place of function calls madewithout \f(CW\*(C`&\*(C'\fR. Calls made using \f(CW\*(C`&\*(C'\fR are never inlined. (See\&\fIconstant.pm\fR for an easy way to declare most constants.).PPThe following functions would all be inlined:.PP.Vb 5\& sub pi () { 3.14159 } # Not exact, but close.\& sub PI () { 4 * atan2 1, 1 } # As good as it gets,\& # and it\*(Aqs inlined, too!\& sub ST_DEV () { 0 }\& sub ST_INO () { 1 }\&\& sub FLAG_FOO () { 1 << 8 }\& sub FLAG_BAR () { 1 << 9 }\& sub FLAG_MASK () { FLAG_FOO | FLAG_BAR }\&\& sub OPT_BAZ () { not (0x1B58 & FLAG_MASK) }\&\& sub N () { int(OPT_BAZ) / 3 }\&\& sub FOO_SET () { 1 if FLAG_MASK & FLAG_FOO }.Ve.PPBe aware that these will not be inlined; as they contain inner scopes,the constant folding doesn't reduce them to a single constant:.PP.Vb 1\& sub foo_set () { if (FLAG_MASK & FLAG_FOO) { 1 } }\&\& sub baz_val () {\& if (OPT_BAZ) {\& return 23;\& }\& else {\& return 42;\& }\& }.Ve.PPIf you redefine a subroutine that was eligible for inlining, you'll geta mandatory warning. (You can use this warning to tell whether or not aparticular subroutine is considered constant.) The warning isconsidered severe enough not to be optional because previously compiledinvocations of the function will still be using the old value of thefunction. If you need to be able to redefine the subroutine, you need toensure that it isn't inlined, either by dropping the \f(CW\*(C`()\*(C'\fR prototype(which changes calling semantics, so beware) or by thwarting theinlining mechanism in some other way, such as.PP.Vb 3\& sub not_inlined () {\& 23 if $];\& }.Ve.Sh "Overriding Built-in Functions".IX Xref "built-in override CORE CORE::GLOBAL".IX Subsection "Overriding Built-in Functions"Many built-in functions may be overridden, though this should be triedonly occasionally and for good reason. Typically this might bedone by a package attempting to emulate missing built-in functionalityon a non-Unix system..PPOverriding may be done only by importing the name from a module atcompile time\*(--ordinary predeclaration isn't good enough. However, the\&\f(CW\*(C`use subs\*(C'\fR pragma lets you, in effect, predeclare subsvia the import syntax, and these names may then override built-in ones:.PP.Vb 3\& use subs \*(Aqchdir\*(Aq, \*(Aqchroot\*(Aq, \*(Aqchmod\*(Aq, \*(Aqchown\*(Aq;\& chdir $somewhere;\& sub chdir { ... }.Ve.PPTo unambiguously refer to the built-in form, precede thebuilt-in name with the special package qualifier \f(CW\*(C`CORE::\*(C'\fR. For example,saying \f(CW\*(C`CORE::open()\*(C'\fR always refers to the built-in \f(CW\*(C`open()\*(C'\fR, evenif the current package has imported some other subroutine called\&\f(CW\*(C`&open()\*(C'\fR from elsewhere. Even though it looks like a regularfunction call, it isn't: you can't take a reference to it, such asthe incorrect \f(CW\*(C`\e&CORE::open\*(C'\fR might appear to produce..PPLibrary modules should not in general export built-in names like \f(CW\*(C`open\*(C'\fRor \f(CW\*(C`chdir\*(C'\fR as part of their default \f(CW@EXPORT\fR list, because these maysneak into someone else's namespace and change the semantics unexpectedly.Instead, if the module adds that name to \f(CW@EXPORT_OK\fR, then it'spossible for a user to import the name explicitly, but not implicitly.That is, they could say.PP.Vb 1\& use Module \*(Aqopen\*(Aq;.Ve.PPand it would import the \f(CW\*(C`open\*(C'\fR override. But if they said.PP.Vb 1\& use Module;.Ve.PPthey would get the default imports without overrides..PPThe foregoing mechanism for overriding built-in is restricted, quitedeliberately, to the package that requests the import. There is a secondmethod that is sometimes applicable when you wish to override a built-ineverywhere, without regard to namespace boundaries. This is achieved byimporting a sub into the special namespace \f(CW\*(C`CORE::GLOBAL::\*(C'\fR. Here is anexample that quite brazenly replaces the \f(CW\*(C`glob\*(C'\fR operator with somethingthat understands regular expressions..PP.Vb 4\& package REGlob;\& require Exporter;\& @ISA = \*(AqExporter\*(Aq;\& @EXPORT_OK = \*(Aqglob\*(Aq;\&\& sub import {\& my $pkg = shift;\& return unless @_;\& my $sym = shift;\& my $where = ($sym =~ s/^GLOBAL_// ? \*(AqCORE::GLOBAL\*(Aq : caller(0));\& $pkg\->export($where, $sym, @_);\& }\&\& sub glob {\& my $pat = shift;\& my @got;\& if (opendir my $d, \*(Aq.\*(Aq) { \& @got = grep /$pat/, readdir $d; \& closedir $d; \& }\& return @got;\& }\& 1;.Ve.PPAnd here's how it could be (ab)used:.PP.Vb 4\& #use REGlob \*(AqGLOBAL_glob\*(Aq; # override glob() in ALL namespaces\& package Foo;\& use REGlob \*(Aqglob\*(Aq; # override glob() in Foo:: only\& print for <^[a\-z_]+\e.pm\e$>; # show all pragmatic modules.Ve.PPThe initial comment shows a contrived, even dangerous example.By overriding \f(CW\*(C`glob\*(C'\fR globally, you would be forcing the new (andsubversive) behavior for the \f(CW\*(C`glob\*(C'\fR operator for \fIevery\fR namespace,without the complete cognizance or cooperation of the modules that ownthose namespaces. Naturally, this should be done with extreme caution\*(--ifit must be done at all..PPThe \f(CW\*(C`REGlob\*(C'\fR example above does not implement all the support needed tocleanly override perl's \f(CW\*(C`glob\*(C'\fR operator. The built-in \f(CW\*(C`glob\*(C'\fR hasdifferent behaviors depending on whether it appears in a scalar or listcontext, but our \f(CW\*(C`REGlob\*(C'\fR doesn't. Indeed, many perl built-in have suchcontext sensitive behaviors, and these must be adequately supported bya properly written override. For a fully functional example of overriding\&\f(CW\*(C`glob\*(C'\fR, study the implementation of \f(CW\*(C`File::DosGlob\*(C'\fR in the standardlibrary..PPWhen you override a built-in, your replacement should be consistent (ifpossible) with the built-in native syntax. You can achieve this by usinga suitable prototype. To get the prototype of an overridable built-in,use the \f(CW\*(C`prototype\*(C'\fR function with an argument of \f(CW"CORE::builtin_name"\fR(see \*(L"prototype\*(R" in perlfunc)..PPNote however that some built-ins can't have their syntax expressed by aprototype (such as \f(CW\*(C`system\*(C'\fR or \f(CW\*(C`chomp\*(C'\fR). If you override them you won'tbe able to fully mimic their original syntax..PPThe built-ins \f(CW\*(C`do\*(C'\fR, \f(CW\*(C`require\*(C'\fR and \f(CW\*(C`glob\*(C'\fR can also be overridden, but dueto special magic, their original syntax is preserved, and you don't haveto define a prototype for their replacements. (You can't override the\&\f(CW\*(C`do BLOCK\*(C'\fR syntax, though)..PP\&\f(CW\*(C`require\*(C'\fR has special additional dark magic: if you invoke your\&\f(CW\*(C`require\*(C'\fR replacement as \f(CW\*(C`require Foo::Bar\*(C'\fR, it will actually receivethe argument \f(CW"Foo/Bar.pm"\fR in \f(CW@_\fR. See \*(L"require\*(R" in perlfunc..PPAnd, as you'll have noticed from the previous example, if you override\&\f(CW\*(C`glob\*(C'\fR, the \f(CW\*(C`<*>\*(C'\fR glob operator is overridden as well..PPIn a similar fashion, overriding the \f(CW\*(C`readline\*(C'\fR function also overridesthe equivalent I/O operator \f(CW\*(C`<FILEHANDLE>\*(C'\fR. Also, overriding\&\f(CW\*(C`readpipe\*(C'\fR also overrides the operators \f(CW\*(C`\`\`\*(C'\fR and \f(CW\*(C`qx//\*(C'\fR..PPFinally, some built-ins (e.g. \f(CW\*(C`exists\*(C'\fR or \f(CW\*(C`grep\*(C'\fR) can't be overridden..Sh "Autoloading".IX Xref "autoloading AUTOLOAD".IX Subsection "Autoloading"If you call a subroutine that is undefined, you would ordinarilyget an immediate, fatal error complaining that the subroutine doesn'texist. (Likewise for subroutines being used as methods, when themethod doesn't exist in any base class of the class's package.)However, if an \f(CW\*(C`AUTOLOAD\*(C'\fR subroutine is defined in the package orpackages used to locate the original subroutine, then that\&\f(CW\*(C`AUTOLOAD\*(C'\fR subroutine is called with the arguments that would havebeen passed to the original subroutine. The fully qualified nameof the original subroutine magically appears in the global \f(CW$AUTOLOAD\fRvariable of the same package as the \f(CW\*(C`AUTOLOAD\*(C'\fR routine. The nameis not passed as an ordinary argument because, er, well, justbecause, that's why. (As an exception, a method call to a nonexistent\&\f(CW\*(C`import\*(C'\fR or \f(CW\*(C`unimport\*(C'\fR method is just skipped instead.).PPMany \f(CW\*(C`AUTOLOAD\*(C'\fR routines load in a definition for the requestedsubroutine using \fIeval()\fR, then execute that subroutine using a specialform of \fIgoto()\fR that erases the stack frame of the \f(CW\*(C`AUTOLOAD\*(C'\fR routinewithout a trace. (See the source to the standard module documentedin AutoLoader, for example.) But an \f(CW\*(C`AUTOLOAD\*(C'\fR routine canalso just emulate the routine and never define it. For example,let's pretend that a function that wasn't defined should just invoke\&\f(CW\*(C`system\*(C'\fR with those arguments. All you'd do is:.PP.Vb 8\& sub AUTOLOAD {\& my $program = $AUTOLOAD;\& $program =~ s/.*:://;\& system($program, @_);\& }\& date();\& who(\*(Aqam\*(Aq, \*(Aqi\*(Aq);\& ls(\*(Aq\-l\*(Aq);.Ve.PPIn fact, if you predeclare functions you want to call that way, you don'teven need parentheses:.PP.Vb 4\& use subs qw(date who ls);\& date;\& who "am", "i";\& ls \*(Aq\-l\*(Aq;.Ve.PPA more complete example of this is the standard Shell module, whichcan treat undefined subroutine calls as calls to external programs..PPMechanisms are available to help modules writers split their modulesinto autoloadable files. See the standard AutoLoader moduledescribed in AutoLoader and in AutoSplit, the standardSelfLoader modules in SelfLoader, and the document on adding Cfunctions to Perl code in perlxs..Sh "Subroutine Attributes".IX Xref "attribute subroutine, attribute attrs".IX Subsection "Subroutine Attributes"A subroutine declaration or definition may have a list of attributesassociated with it. If such an attribute list is present, it isbroken up at space or colon boundaries and treated as though a\&\f(CW\*(C`use attributes\*(C'\fR had been seen. See attributes for detailsabout what attributes are currently supported.Unlike the limitation with the obsolescent \f(CW\*(C`use attrs\*(C'\fR, the\&\f(CW\*(C`sub : ATTRLIST\*(C'\fR syntax works to associate the attributes witha p
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -