⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ch06_05.htm

📁 编程珍珠,里面很多好用的代码,大家可以参考学习呵呵,
💻 HTM
字号:
<html><head><title>Subroutine Attributes (Programming Perl)</title><!-- STYLESHEET --><link rel="stylesheet" type="text/css" href="../style/style1.css"><!-- METADATA --><!--Dublin Core Metadata--><meta name="DC.Creator" content=""><meta name="DC.Date" content=""><meta name="DC.Format" content="text/xml" scheme="MIME"><meta name="DC.Generator" content="XSLT stylesheet, xt by James Clark"><meta name="DC.Identifier" content=""><meta name="DC.Language" content="en-US"><meta name="DC.Publisher" content="O'Reilly &amp; Associates, Inc."><meta name="DC.Source" content="" scheme="ISBN"><meta name="DC.Subject.Keyword" content=""><meta name="DC.Title" content="Subroutine Attributes"><meta name="DC.Type" content="Text.Monograph"></head><body><!-- START OF BODY --><!-- TOP BANNER --><img src="gifs/smbanner.gif" usemap="#banner-map" border="0" alt="Book Home"><map name="banner-map"><AREA SHAPE="RECT" COORDS="0,0,466,71" HREF="index.htm" ALT="Programming Perl"><AREA SHAPE="RECT" COORDS="467,0,514,18" HREF="jobjects/fsearch.htm" ALT="Search this book"></map><!-- TOP NAV BAR --><div class="navbar"><table width="515" border="0"><tr><td align="left" valign="top" width="172"><a href="ch06_04.htm"><img src="../gifs/txtpreva.gif" alt="Previous" border="0"></a></td><td align="center" valign="top" width="171"><a href="ch06_01.htm">Chapter 6: Subroutines</a></td><td align="right" valign="top" width="172"><a href="ch07_01.htm"><img src="../gifs/txtnexta.gif" alt="Next" border="0"></a></td></tr></table></div><hr width="515" align="left"><!-- SECTION BODY --><h2 class="sect1">6.5. Subroutine Attributes</h2><p><a name="INDEX-1872"></a><a name="INDEX-1873"></a><a name="INDEX-1874"></a><a name="INDEX-1875"></a><a name="INDEX-1876"></a><a name="INDEX-1877"></a>A subroutine declaration or definition may have a list of attributesassociated with it.  If such an attribute list is present, it isbroken up at whitespace or colon boundaries and treated as thougha <tt class="literal">use attributes</tt> had been seen.  See the <tt class="literal">use attributes</tt> pragmain <a href="ch31_01.htm">Chapter 31, "Pragmatic Modules"</a> for internal details.  There are threestandard attributes for subroutines: <tt class="literal">locked</tt>, <tt class="literal">method</tt>, and<tt class="literal">lvalue</tt>.</p><a name="ch06-sect-locked"></a><h3 class="sect2">6.5.1. The locked and method Attributes</h3><p><blockquote><pre class="programlisting"># Only one thread is allowed into this function.sub afunc : locked { ... }# Only one thread is allowed into this function on a given object.sub afunc : locked method { ... }</pre></blockquote>Setting the <tt class="literal">locked</tt> attribute is meaningful only when the subroutine ormethod is intended to be called by multiple threads simultaneously.When set on a nonmethod subroutine, Perl ensures that a lock isacquired on the subroutine itself before that subroutine is entered.When set on a method subroutine (that is, one also marked with the<tt class="literal">method</tt> attribute), Perl ensures that any invocation of itimplicitly locks its first argument (the object) before execution.</p><p>Semantics of this lock are the same as using the <tt class="literal">lock</tt> operator onthe subroutine as the first statement in that routine.  See <a href="ch17_01.htm">Chapter 17, "Threads"</a>, for more on locking.</p><p>The <tt class="literal">method</tt> attribute can be used by itself:<blockquote><pre class="programlisting">sub afunc : method { ... }</pre></blockquote>Currently this has only the effect of marking the subroutineso as not to trigger the "<tt class="literal">Ambiguous call resolved asCORE::%s</tt>" warning.  (We may make it mean more someday.)</p><p><a name="INDEX-1878"></a><a name="INDEX-1879"></a>The attribute system is user-extensible, letting you create your ownattribute names.  These new attributes must be valid as simpleidentifier names (without any punctuation other than the "<tt class="literal">_</tt>"character).  They may have a parameter list appended, which is currentlyonly checked for whether its parentheses nest properly.</p><p>Here are examples of valid syntax (even though the attributes are unknown):<blockquote><pre class="programlisting">sub fnord (&amp;\%) : switch(10,foo(7,3))  :  expensive;sub plugh () : Ugly('\(") :Bad;sub xyzzy : _5x5 { ... }</pre></blockquote>Here are examples of invalid syntax:<blockquote><pre class="programlisting">sub fnord : switch(10,foo();  # ()-string not balancedsub snoid : Ugly('(');        # ()-string not balancedsub xyzzy : 5x5;              # "5x5" not a valid identifiersub plugh : Y2::north;        # "Y2::north" not a simple identifiersub snurt : foo + bar;        # "+" not a colon or space</pre></blockquote>The attribute list is passed as a list of constant strings to the codethat associates them with the subroutine.  Exactly how this works (ordoesn't) is highly experimental.  Check<em class="emphasis">attributes</em>(3) for current details on attribute lists and theirmanipulation.</p><a name="ch06-sect-lvalue"></a><h3 class="sect2">6.5.2. The lvalue Attribute</h3><p><a name="INDEX-1880"></a>It is possible to return a modifiable scalar value from a subroutine, butonly if you declare the subroutine to return an lvalue:<blockquote><pre class="programlisting">my $val;sub canmod : lvalue {    $val;}sub nomod {    $val;}canmod() = 5;   # Assigns to $val.nomod()  = 5;   # ERROR</pre></blockquote>If you're passing parameters to an lvalued subroutine, you'll usuallywant parentheses to disambiguate what's being assigned:<blockquote><pre class="programlisting">canmod $x  = 5;     # assigns 5 to $x first!canmod 42  = 5;     # can't change a constant; compile-time errorcanmod($x) = 5;     # this is okcanmod(42) = 5;     # and so is this</pre></blockquote>If you want to be sneaky, you can get around this in the particularcase of a subroutine that takes one argument.  Declaring the functionwith a prototype of <tt class="literal">($)</tt> causes the function to be parsed with theprecedence of a named unary operator.  Since named unaries have higherprecedence than assignment, you no longer need the parentheses.(Whether this is desirable or not is left up to the style police.)</p><p>You don't have to be sneaky in the particular case of a subroutinethat allows zero arguments (that is, with a <tt class="literal">()</tt>prototype).  You can without ambiguity say this:<blockquote><pre class="programlisting">canmod = 5;</pre></blockquote>That works because no valid term begins with <tt class="literal">=</tt>.  Similarly, lvaluedmethod calls can omit the parentheses when you don't pass anyarguments:<blockquote><pre class="programlisting">$obj-&gt;canmod = 5;</pre></blockquote>We promise not to break those two constructs in future versions ofPerl.  They're handy when you want to wrap object attributes in methodcalls (so that they can be inherited like method calls but accessed like variables).</p><p>The scalar or list context of both the lvalue subroutine and therighthand side of an assignment to that subroutine is determined asif the subroutine call were replaced by a scalar. For example,consider:<blockquote><pre class="programlisting">data(2,3) = get_data(3,4);</pre></blockquote>Both subroutines here are called in scalar context, while in:<blockquote><pre class="programlisting">(data(2,3)) = get_data(3,4);</pre></blockquote>and in:<blockquote><pre class="programlisting">(data(2),data(3)) = get_data(3,4);</pre></blockquote>all the subroutines are called in list context.</p><p>The current implementation does not allow arrays and hashes to bereturned from lvalue subroutines directly.  You can always return areference instead.<a name="INDEX-1881"></a><a name="INDEX-1882"></a></p><!-- BOTTOM NAV BAR --><hr width="515" align="left"><div class="navbar"><table width="515" border="0"><tr><td align="left" valign="top" width="172"><a href="ch06_04.htm"><img src="../gifs/txtpreva.gif" alt="Previous" border="0"></a></td><td align="center" valign="top" width="171"><a href="index.htm"><img src="../gifs/txthome.gif" alt="Home" border="0"></a></td><td align="right" valign="top" width="172"><a href="ch07_01.htm"><img src="../gifs/txtnexta.gif" alt="Next" border="0"></a></td></tr><tr><td align="left" valign="top" width="172">6.4. Prototypes</td><td align="center" valign="top" width="171"><a href="index/index.htm"><img src="../gifs/index.gif" alt="Book Index" border="0"></a></td><td align="right" valign="top" width="172">7. Formats</td></tr></table></div><hr width="515" align="left"><!-- LIBRARY NAV BAR --><img src="../gifs/smnavbar.gif" usemap="#library-map" border="0" alt="Library Navigation Links"><p><font size="-1"><a href="copyrght.htm">Copyright &copy; 2001</a> O'Reilly &amp; Associates. All rights reserved.</font></p><map name="library-map"> <area shape="rect" coords="2,-1,79,99" href="../index.htm"><area shape="rect" coords="84,1,157,108" href="../perlnut/index.htm"><area shape="rect" coords="162,2,248,125" href="../prog/index.htm"><area shape="rect" coords="253,2,326,130" href="../advprog/index.htm"><area shape="rect" coords="332,1,407,112" href="../cookbook/index.htm"><area shape="rect" coords="414,2,523,103" href="../sysadmin/index.htm"></map><!-- END OF BODY --></body></html>

⌨️ 快捷键说明

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