perltoot.html
来自「perl教程」· HTML 代码 · 共 771 行 · 第 1/5 页
HTML
771 行
argument, they set the appropriate field; otherwise they return the
value held by that field, meaning the value of that hash key.</p>
<p>
</p>
<h2><a name="planning_for_the_future__better_constructors">Planning for the Future: Better Constructors</a></h2>
<p>Even though at this point you may not even know what it means, someday
you're going to worry about inheritance. (You can safely ignore this
for now and worry about it later if you'd like.) To ensure that this
all works out smoothly, you must use the double-argument form of bless().
The second argument is the class into which the referent will be blessed.
By not assuming our own class as the default second argument and instead
using the class passed into us, we make our constructor inheritable.</p>
<pre>
<span class="keyword">sub</span><span class="variable"> new </span><span class="operator">{</span>
<span class="keyword">my</span> <span class="variable">$class</span> <span class="operator">=</span> <span class="keyword">shift</span><span class="operator">;</span>
<span class="keyword">my</span> <span class="variable">$self</span> <span class="operator">=</span> <span class="operator">{}</span><span class="operator">;</span>
<span class="variable">$self</span><span class="operator">-></span><span class="operator">{</span><span class="string">NAME</span><span class="operator">}</span> <span class="operator">=</span> <span class="keyword">undef</span><span class="operator">;</span>
<span class="variable">$self</span><span class="operator">-></span><span class="operator">{</span><span class="string">AGE</span><span class="operator">}</span> <span class="operator">=</span> <span class="keyword">undef</span><span class="operator">;</span>
<span class="variable">$self</span><span class="operator">-></span><span class="operator">{</span><span class="string">PEERS</span><span class="operator">}</span> <span class="operator">=</span> <span class="operator">[]</span><span class="operator">;</span>
<span class="keyword">bless</span> <span class="operator">(</span><span class="variable">$self</span><span class="operator">,</span> <span class="variable">$class</span><span class="operator">);</span>
<span class="keyword">return</span> <span class="variable">$self</span><span class="operator">;</span>
<span class="operator">}</span>
</pre>
<p>That's about all there is for constructors. These methods bring objects
to life, returning neat little opaque bundles to the user to be used in
subsequent method calls.</p>
<p>
</p>
<h2><a name="destructors">Destructors</a></h2>
<p>Every story has a beginning and an end. The beginning of the object's
story is its constructor, explicitly called when the object comes into
existence. But the ending of its story is the <em>destructor</em>, a method
implicitly called when an object leaves this life. Any per-object
clean-up code is placed in the destructor, which must (in Perl) be called
DESTROY.</p>
<p>If constructors can have arbitrary names, then why not destructors?
Because while a constructor is explicitly called, a destructor is not.
Destruction happens automatically via Perl's garbage collection (GC)
system, which is a quick but somewhat lazy reference-based GC system.
To know what to call, Perl insists that the destructor be named DESTROY.
Perl's notion of the right time to call a destructor is not well-defined
currently, which is why your destructors should not rely on when they are
called.</p>
<p>Why is DESTROY in all caps? Perl on occasion uses purely uppercase
function names as a convention to indicate that the function will
be automatically called by Perl in some way. Others that are called
implicitly include BEGIN, END, AUTOLOAD, plus all methods used by
tied objects, described in <a href="../../lib/Pod/perltie.html">the perltie manpage</a>.</p>
<p>In really good object-oriented programming languages, the user doesn't
care when the destructor is called. It just happens when it's supposed
to. In low-level languages without any GC at all, there's no way to
depend on this happening at the right time, so the programmer must
explicitly call the destructor to clean up memory and state, crossing
their fingers that it's the right time to do so. Unlike C++, an
object destructor is nearly never needed in Perl, and even when it is,
explicit invocation is uncalled for. In the case of our Person class,
we don't need a destructor because Perl takes care of simple matters
like memory deallocation.</p>
<p>The only situation where Perl's reference-based GC won't work is
when there's a circularity in the data structure, such as:</p>
<pre>
<span class="variable">$this</span><span class="operator">-></span><span class="operator">{</span><span class="string">WHATEVER</span><span class="operator">}</span> <span class="operator">=</span> <span class="variable">$this</span><span class="operator">;</span>
</pre>
<p>In that case, you must delete the self-reference manually if you expect
your program not to leak memory. While admittedly error-prone, this is
the best we can do right now. Nonetheless, rest assured that when your
program is finished, its objects' destructors are all duly called.
So you are guaranteed that an object <em>eventually</em> gets properly
destroyed, except in the unique case of a program that never exits.
(If you're running Perl embedded in another application, this full GC
pass happens a bit more frequently--whenever a thread shuts down.)</p>
<p>
</p>
<h2><a name="other_object_methods">Other Object Methods</a></h2>
<p>The methods we've talked about so far have either been constructors or
else simple "data methods", interfaces to data stored in the object.
These are a bit like an object's data members in the C++ world, except
that strangers don't access them as data. Instead, they should only
access the object's data indirectly via its methods. This is an
important rule: in Perl, access to an object's data should <em>only</em>
be made through methods.</p>
<p>Perl doesn't impose restrictions on who gets to use which methods.
The public-versus-private distinction is by convention, not syntax.
(Well, unless you use the Alias module described below in
<a href="#data_members_as_variables">Data Members as Variables</a>.) Occasionally you'll see method names beginning or ending
with an underscore or two. This marking is a convention indicating
that the methods are private to that class alone and sometimes to its
closest acquaintances, its immediate subclasses. But this distinction
is not enforced by Perl itself. It's up to the programmer to behave.</p>
<p>There's no reason to limit methods to those that simply access data.
Methods can do anything at all. The key point is that they're invoked
against an object or a class. Let's say we'd like object methods that
do more than fetch or set one particular field.</p>
<pre>
<span class="keyword">sub</span><span class="variable"> exclaim </span><span class="operator">{</span>
<span class="keyword">my</span> <span class="variable">$self</span> <span class="operator">=</span> <span class="keyword">shift</span><span class="operator">;</span>
<span class="keyword">return</span> <span class="keyword">sprintf</span> <span class="string">"Hi, I'm %s, age %d, working with %s"</span><span class="operator">,</span>
<span class="variable">$self</span><span class="operator">-></span><span class="operator">{</span><span class="string">NAME</span><span class="operator">}</span><span class="operator">,</span> <span class="variable">$self</span><span class="operator">-></span><span class="operator">{</span><span class="string">AGE</span><span class="operator">}</span><span class="operator">,</span> <span class="keyword">join</span><span class="operator">(</span><span class="string">", "</span><span class="operator">,</span> <span class="variable">@</span><span class="operator">{</span><span class="variable">$self</span><span class="operator">-></span><span class="operator">{</span><span class="string">PEERS</span><span class="operator">}}</span><span class="operator">);</span>
<span class="operator">}</span>
</pre>
<p>Or maybe even one like this:</p>
<pre>
<span class="keyword">sub</span><span class="variable"> happy_birthday </span><span class="operator">{</span>
<span class="keyword">my</span> <span class="variable">$self</span> <span class="operator">=</span> <span class="keyword">shift</span><span class="operator">;</span>
<span class="keyword">return</span> <span class="operator">++</span><span class="variable">$self</span><span class="operator">-></span><span class="operator">{</span><span class="string">AGE</span><span class="operator">}</span><span class="operator">;</span>
<span class="operator">}</span>
</pre>
<p>Some might argue that one should go at these this way:</p>
<pre>
<span class="keyword">sub</span><span class="variable"> exclaim </span><span class="operator">{</span>
<span class="keyword">my</span> <span class="variable">$self</span> <span class="operator">=</span> <span class="keyword">shift</span><span class="operator">;</span>
<span class="keyword">return</span> <span class="keyword">sprintf</span> <span class="string">"Hi, I'm %s, age %d, working with %s"</span><span class="operator">,</span>
<span class="variable">$self</span><span class="operator">-></span><span class="variable">name</span><span class="operator">,</span> <span class="variable">$self</span><span class="operator">-></span><span class="variable">age</span><span class="operator">,</span> <span class="keyword">join</span><span class="operator">(</span><span class="string">", "</span><span class="operator">,</span> <span class="variable">$self</span><span class="operator">-></span><span class="variable">peers</span><span class="operator">);</span>
<span class="operator">}</span>
</pre>
<pre>
<span class="keyword">sub</span><span class="variable"> happy_birthday </span><span class="operator">{</span>
<span class="keyword">my</span> <span class="variable">$self</span> <span class="operator">=</span> <span class="keyword">shift</span><span class="operator">;</span>
<span class="keyword">return</span> <span class="variable">$self</span><span class="operator">-></span><span class="variable">age</span><span class="operator">(</span> <span class="variable">$self</span><span class="operator">-></span><span class="variable">age</span><span class="operator">()</span> <span class="operator">+</span> <span class="number">1</span> <span class="operator">);</span>
<span class="operator">}</span>
</pre>
<p>But since these methods are all executing in the class itself, this
may not be critical. There are tradeoffs to be made. Using direct
hash access is faster (about an order of magnitude faster, in fact), and
it's more convenient when you want to interpolate in strings. But using
methods (the external interface) internally shields not just the users of
your class but even you yourself from changes in your data representation.</p>
<p>
</p>
<hr />
<h1><a name="class_data">Class Data</a></h1>
<p>What about "class data", data items common to each object in a class?
What would you want that for? Well, in your Person class, you might
like to keep track of the total people alive. How do you implement that?</p>
<p>You <em>could</em> make it a global variable called $Person::Census. But about
only reason you'd do that would be if you <em>wanted</em> people to be able to
get at your class data directly. They could just say $Person::Census
and play around with it. Maybe this is ok in your design scheme.
You might even conceivably want to make it an exported variable. To be
exportable, a variable must be a (package) global. If this were a
traditional module rather than an object-oriented one, you might do that.</p>
<p>While this approach is expected in most traditional modules, it's
generally considered rather poor form in most object modules. In an
object module, you should set up a protective veil to separate interface
from implementation. So provide a class method to access class data
just as you provide object methods to access object data.</p>
<p>So, you <em>could</em> still keep $Census as a package global and rely upon
others to honor the contract of the module and therefore not play around
with its implementation. You could even be supertricky and make $Census a
tied object as described in <a href="../../lib/Pod/perltie.html">the perltie manpage</a>, thereby intercepting all accesses.</p>
<p>But more often than not, you just want to make your class data a
file-scoped lexical. To do so, simply put this at the top of the file:</p>
<pre>
<span class="keyword">my</span> <span class="variable">$Census</span> <span class="operator">=</span> <span class="number">0</span><span class="operator">;</span>
</pre>
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?