📄 ch10_15.htm
字号:
<HTML><HEAD><TITLE>Recipe 10.14. Redefining a Function (Perl Cookbook)</TITLE><METANAME="DC.title"CONTENT="Perl Cookbook"><METANAME="DC.creator"CONTENT="Tom Christiansen & Nathan Torkington"><METANAME="DC.publisher"CONTENT="O'Reilly & Associates, Inc."><METANAME="DC.date"CONTENT="1999-07-02T01:40:05Z"><METANAME="DC.type"CONTENT="Text.Monograph"><METANAME="DC.format"CONTENT="text/html"SCHEME="MIME"><METANAME="DC.source"CONTENT="1-56592-243-3"SCHEME="ISBN"><METANAME="DC.language"CONTENT="en-US"><METANAME="generator"CONTENT="Jade 1.1/O'Reilly DocBook 3.0 to HTML 4.0"><LINKREV="made"HREF="mailto:online-books@oreilly.com"TITLE="Online Books Comments"><LINKREL="up"HREF="ch10_01.htm"TITLE="10. Subroutines"><LINKREL="prev"HREF="ch10_14.htm"TITLE="10.13. Saving Global Values"><LINKREL="next"HREF="ch10_16.htm"TITLE="10.15. Trapping Undefined Function Calls with AUTOLOAD"></HEAD><BODYBGCOLOR="#FFFFFF"><img alt="Book Home" border="0" src="gifs/smbanner.gif" usemap="#banner-map" /><map name="banner-map"><area shape="rect" coords="1,-2,616,66" href="index.htm" alt="Perl Cookbook"><area shape="rect" coords="629,-11,726,25" href="jobjects/fsearch.htm" alt="Search this book" /></map><div class="navbar"><p><TABLEWIDTH="684"BORDER="0"CELLSPACING="0"CELLPADDING="0"><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch10_14.htm"TITLE="10.13. Saving Global Values"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 10.13. Saving Global Values"BORDER="0"></A></TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><B><FONTFACE="ARIEL,HELVETICA,HELV,SANSERIF"SIZE="-1"><ACLASS="chapter"REL="up"HREF="ch10_01.htm"TITLE="10. Subroutines"></A></FONT></B></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch10_16.htm"TITLE="10.15. Trapping Undefined Function Calls with AUTOLOAD"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 10.15. Trapping Undefined Function Calls with AUTOLOAD"BORDER="0"></A></TD></TR></TABLE></DIV><DIVCLASS="sect1"><H2CLASS="sect1"><ACLASS="title"NAME="ch10-24176">10.14. Redefining a Function</A></H2><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch10-pgfId-1000005610">Problem</A></H3><PCLASS="para"><ACLASS="indexterm"NAME="ch10-idx-1000004739-0"></A><ACLASS="indexterm"NAME="ch10-idx-1000004739-1"></A><ACLASS="indexterm"NAME="ch10-idx-1000004739-2"></A>You want to temporarily or permanently redefine a function, but functions can't be assigned to.</P></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch10-pgfId-1062">Solution</A></H3><PCLASS="para">To redefine a function, assign a new code reference to the typeglob of the name of the function. Use a <CODECLASS="literal">local</CODE> if you want it to be temporary.</P><PRECLASS="programlisting">undef &grow; # silence -w complaints of redefinition*grow = \&expand; grow(); # calls expand(){ local *grow = \&shrink; # only until this block exists grow(); # calls shrink()}</PRE></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch10-pgfId-1084">Discussion</A></H3><PCLASS="para">Unlike a variable but like a handle, a function cannot be directly assigned to. It's just a name. You can manipulate it almost as though it were a variable, because you can directly manipulate the run-time symbol table using typeglobs like <CODECLASS="literal">*foo</CODE> to produce interesting <ACLASS="indexterm"NAME="ch10-idx-1000006373-0"></A>aliasing effects.</P><PCLASS="para">Assigning a reference to a typeglob changes what is accessed the next time a symbol of that type is needed. This is what the Exporter does when you <ACLASS="indexterm"NAME="ch10-idx-1000006380-0"></A>import a function or variable from one package into another. Since this is direct manipulation of the package symbol table, it only works on package variables (globals), not lexicals.</P><PRECLASS="programlisting">*one::var = \%two::Table; # make %one::var alias for %two::Table*one::big = \&two::small; # make &one::big alias for &two::small</PRE><PCLASS="para">A typeglob is something you can use <CODECLASS="literal">local</CODE> on, but not <CODECLASS="literal">my</CODE>. Because of the <CODECLASS="literal">local</CODE>, this aliasing effect is then limited to the duration of the current block.</P><PRECLASS="programlisting">local *fred = \&barney; # temporarily alias &fred to &barney</PRE><PCLASS="para">If the value assigned to a typeglob is not a reference but itself another typeglob, then <EMCLASS="emphasis">all</EM> types by that name are aliased. The types aliased in a full typeglob assignment are scalar, array, hash, function, filehandle, directory handle, and format. That means that assigning <CODECLASS="literal">*Top</CODE> <CODECLASS="literal">=</CODE> <CODECLASS="literal">*Bottom</CODE> would make the current package variable <CODECLASS="literal">$Top</CODE> an alias for <CODECLASS="literal">$Bottom</CODE>, <CODECLASS="literal">@Top</CODE> for <CODECLASS="literal">@Bottom</CODE>, <CODECLASS="literal">%Top</CODE> for <CODECLASS="literal">%Bottom</CODE>, and <CODECLASS="literal">&Top</CODE> for <CODECLASS="literal">&Bottom</CODE>. It would even alias the corresponding file and directory handles and formats! You probably don't want to do this.</P><PCLASS="para">Use assignments to typeglobs together with closures to clone a bunch of similar functions cheaply and easily. Imagine you wanted a function for HTML generation to help with colors. For example:</P><PRECLASS="programlisting">$string = red("careful here");print $string;<CODECLASS="userinput"><B><CODECLASS="replaceable"><I><FONT COLOR='red'>careful here</FONT></I></CODE></B></CODE></PRE><PCLASS="para">You could write the <CODECLASS="literal">red </CODE> function this way:</P><PRECLASS="programlisting">sub red { "<FONT COLOR='red'>@_</FONT>" }</PRE><PCLASS="para">If you need more colors, you could do something like this:</P><PRECLASS="programlisting">sub color_font { my $color = shift; return "<FONT COLOR='$color'>@_</FONT>";}sub red { color_font("red", @_) }sub green { color_font("green", @_) }sub blue { color_font("blue", @_) }sub purple { color_font("purple", @_) }# etc</PRE><PCLASS="para">The similar nature of these functions suggests that there may be a way to factor out the common bit. To do this, use an assignment to an indirect typeglob. If you're running with the highly recommended <CODECLASS="literal">use</CODE> <CODECLASS="literal">strict</CODE> pragma, you must first disable <CODECLASS="literal">strict 'refs'</CODE> for that block.</P><PRECLASS="programlisting">@colors = qw(red blue green yellow orange purple violet);for my $name (@colors) { no strict 'refs'; *$name = sub { "<FONT COLOR='$name'>@_</FONT>" };} </PRE><PCLASS="para">These functions all seem independent, but the real code was in fact only compiled once. This technique saves on both compile time and memory use. To create a proper closure, any variables in the anonymous subroutine <EMCLASS="emphasis">must</EM> be lexicals. That's the reason for the <CODECLASS="literal">my</CODE> on the loop iteration variable.</P><PCLASS="para">This is one of the few places where giving a prototype to a closure is sensible. If you wanted to impose scalar context on the arguments of these functions (probably not a wise idea), you could have written it this way instead:</P><PRECLASS="programlisting">*$name = sub ($) { "<FONT COLOR='$name'>$_[0]</FONT>" };</PRE><PCLASS="para">However, since prototype checking happens at compile time, the preceding assignment happens too late to be useful. So, put the whole loop of assignments within a BEGIN block, forcing it to occur during compilation.<ACLASS="indexterm"NAME="ch10-idx-1000004741-0"></A><ACLASS="indexterm"NAME="ch10-idx-1000004741-1"></A><ACLASS="indexterm"NAME="ch10-idx-1000004741-2"></A> <ACLASS="indexterm"NAME="ch10-idx-1000006406-0"></A></P></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch10-pgfId-1000005636">See Also</A></H3><PCLASS="para">The sections on <ACLASS="olink"HREF="../prog/ch05_01.htm#PERL2-CH-5-SECT-1.1">"Symbol Tables"</A> in <ACLASS="olink"HREF="../prog/ch05_01.htm">Chapter 5</A> of <ACLASS="citetitle"HREF="../prog/index.htm"TITLE="Programming Perl"><CITECLASS="citetitle">Programming Perl</CITE></A> and in <ICLASS="filename">perlmod </I>(1); the section on <ACLASS="olink"HREF="../prog/ch04_03.htm#PERL2-CH-4-SECT-3.6">"Closures"</A> in <ACLASS="olink"HREF="../prog/ch04_01.htm">Chapter 4</A> of <ACLASS="citetitle"HREF="../prog/index.htm"TITLE="Programming Perl"><CITECLASS="citetitle">Programming Perl</CITE></A> and the discussion of closures in <ICLASS="filename">perlref </I>(1); <ACLASS="xref"HREF="ch10_12.htm"TITLE="Prototyping Functions">Recipe 10.11</A>; <ACLASS="xref"HREF="ch11_05.htm"TITLE="Taking References to Functions">Recipe 11.4</A></P></DIV></DIV><DIVCLASS="htmlnav"><P></P><HRALIGN="LEFT"WIDTH="684"TITLE="footer"><TABLEWIDTH="684"BORDER="0"CELLSPACING="0"CELLPADDING="0"><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch10_14.htm"TITLE="10.13. Saving Global Values"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 10.13. Saving Global Values"BORDER="0"></A></TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><ACLASS="book"HREF="index.htm"TITLE="Perl Cookbook"><IMGSRC="../gifs/txthome.gif"ALT="Perl Cookbook"BORDER="0"></A></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch10_16.htm"TITLE="10.15. Trapping Undefined Function Calls with AUTOLOAD"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 10.15. Trapping Undefined Function Calls with AUTOLOAD"BORDER="0"></A></TD></TR><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228">10.13. Saving Global Values</TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><ACLASS="index"HREF="index/index.htm"TITLE="Book Index"><IMGSRC="../gifs/index.gif"ALT="Book Index"BORDER="0"></A></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228">10.15. Trapping Undefined Function Calls with AUTOLOAD</TD></TR></TABLE><HRALIGN="LEFT"WIDTH="684"TITLE="footer"><FONTSIZE="-1"></DIV<!-- LIBRARY NAV BAR --> <img src="../gifs/smnavbar.gif" usemap="#library-map" border="0" alt="Library Navigation Links"><p> <a href="copyrght.htm">Copyright © 2002</a> O'Reilly & Associates. All rights reserved.</font> </p> <map name="library-map"> <area shape="rect" coords="1,0,85,94" href="../index.htm"><area shape="rect" coords="86,1,178,103" href="../lwp/index.htm"><area shape="rect" coords="180,0,265,103" href="../lperl/index.htm"><area shape="rect" coords="267,0,353,105" href="../perlnut/index.htm"><area shape="rect" coords="354,1,446,115" href="../prog/index.htm"><area shape="rect" coords="448,0,526,132" href="../tk/index.htm"><area shape="rect" coords="528,1,615,119" href="../cookbook/index.htm"><area shape="rect" coords="617,0,690,135" href="../pxml/index.htm"></map> </BODY></HTML>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -