Install Perl 5.8.8
[msysgit.git] / mingw / html / pod / perlobj.html
blobc9b99975d8fab85272110f12e4e9460adedc2c99
1 <?xml version="1.0" ?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3 <html xmlns="http://www.w3.org/1999/xhtml">
4 <head>
5 <title>perlobj - Perl objects</title>
6 <meta http-equiv="content-type" content="text/html; charset=utf-8" />
7 <link rev="made" href="mailto:" />
8 </head>
10 <body style="background-color: white">
11 <table border="0" width="100%" cellspacing="0" cellpadding="3">
12 <tr><td class="block" style="background-color: #cccccc" valign="middle">
13 <big><strong><span class="block">&nbsp;perlobj - Perl objects</span></strong></big>
14 </td></tr>
15 </table>
17 <p><a name="__index__"></a></p>
18 <!-- INDEX BEGIN -->
20 <ul>
22 <li><a href="#name">NAME</a></li>
23 <li><a href="#description">DESCRIPTION</a></li>
24 <ul>
26 <li><a href="#an_object_is_simply_a_reference">An Object is Simply a Reference</a></li>
27 <li><a href="#a_class_is_simply_a_package">A Class is Simply a Package</a></li>
28 <li><a href="#a_method_is_simply_a_subroutine">A Method is Simply a Subroutine</a></li>
29 <li><a href="#method_invocation">Method Invocation</a></li>
30 <li><a href="#indirect_object_syntax">Indirect Object Syntax</a></li>
31 <li><a href="#default_universal_methods">Default UNIVERSAL methods</a></li>
32 <li><a href="#destructors">Destructors</a></li>
33 <li><a href="#summary">Summary</a></li>
34 <li><a href="#twophased_garbage_collection">Two-Phased Garbage Collection</a></li>
35 </ul>
37 <li><a href="#see_also">SEE ALSO</a></li>
38 </ul>
39 <!-- INDEX END -->
41 <hr />
42 <p>
43 </p>
44 <h1><a name="name_x_object__x_oop_">NAME
45 </a></h1>
46 <p>perlobj - Perl objects</p>
47 <p>
48 </p>
49 <hr />
50 <h1><a name="description">DESCRIPTION</a></h1>
51 <p>First you need to understand what references are in Perl.
52 See <a href="file://C|\msysgit\mingw\html/pod/perlref.html">the perlref manpage</a> for that. Second, if you still find the following
53 reference work too complicated, a tutorial on object-oriented programming
54 in Perl can be found in <a href="file://C|\msysgit\mingw\html/pod/perltoot.html">the perltoot manpage</a> and <a href="file://C|\msysgit\mingw\html/pod/perltooc.html">the perltooc manpage</a>.</p>
55 <p>If you're still with us, then
56 here are three very simple definitions that you should find reassuring.</p>
57 <ol>
58 <li>
59 <p>An object is simply a reference that happens to know which class it
60 belongs to.</p>
61 </li>
62 <li>
63 <p>A class is simply a package that happens to provide methods to deal
64 with object references.</p>
65 </li>
66 <li>
67 <p>A method is simply a subroutine that expects an object reference (or
68 a package name, for class methods) as the first argument.</p>
69 </li>
70 </ol>
71 <p>We'll cover these points now in more depth.</p>
72 <p>
73 </p>
74 <h2><a name="an_object_is_simply_a_reference_x_object__x_bless__x_constructor__x_new_">An Object is Simply a Reference
75 </a></h2>
76 <p>Unlike say C++, Perl doesn't provide any special syntax for
77 constructors. A constructor is merely a subroutine that returns a
78 reference to something ``blessed'' into a class, generally the
79 class that the subroutine is defined in. Here is a typical
80 constructor:</p>
81 <pre>
82 package Critter;
83 sub new { bless {} }</pre>
84 <p>That word <code>new</code> isn't special. You could have written
85 a construct this way, too:</p>
86 <pre>
87 package Critter;
88 sub spawn { bless {} }</pre>
89 <p>This might even be preferable, because the C++ programmers won't
90 be tricked into thinking that <code>new</code> works in Perl as it does in C++.
91 It doesn't. We recommend that you name your constructors whatever
92 makes sense in the context of the problem you're solving. For example,
93 constructors in the Tk extension to Perl are named after the widgets
94 they create.</p>
95 <p>One thing that's different about Perl constructors compared with those in
96 C++ is that in Perl, they have to allocate their own memory. (The other
97 things is that they don't automatically call overridden base-class
98 constructors.) The <code>{}</code> allocates an anonymous hash containing no
99 key/value pairs, and returns it The <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_bless"><code>bless()</code></a> takes that reference and
100 tells the object it references that it's now a Critter, and returns
101 the reference. This is for convenience, because the referenced object
102 itself knows that it has been blessed, and the reference to it could
103 have been returned directly, like this:</p>
104 <pre>
105 sub new {
106 my $self = {};
107 bless $self;
108 return $self;
109 }</pre>
110 <p>You often see such a thing in more complicated constructors
111 that wish to call methods in the class as part of the construction:</p>
112 <pre>
113 sub new {
114 my $self = {};
115 bless $self;
116 $self-&gt;initialize();
117 return $self;
118 }</pre>
119 <p>If you care about inheritance (and you should; see
120 <a href="file://C|\msysgit\mingw\html/pod/perlmodlib.html#modules__creation__use__and_abuse">Modules: Creation, Use, and Abuse in the perlmodlib manpage</a>),
121 then you want to use the two-arg form of bless
122 so that your constructors may be inherited:</p>
123 <pre>
124 sub new {
125 my $class = shift;
126 my $self = {};
127 bless $self, $class;
128 $self-&gt;initialize();
129 return $self;
130 }</pre>
131 <p>Or if you expect people to call not just <code>CLASS-&gt;new()</code> but also
132 <code>$obj-&gt;new()</code>, then use something like the following. (Note that using
133 this to call <code>new()</code> on an instance does not automatically perform any
134 copying. If you want a shallow or deep copy of an object, you'll have to
135 specifically allow for that.) The <code>initialize()</code> method used will be of
136 whatever $class we blessed the object into:</p>
137 <pre>
138 sub new {
139 my $this = shift;
140 my $class = ref($this) || $this;
141 my $self = {};
142 bless $self, $class;
143 $self-&gt;initialize();
144 return $self;
145 }</pre>
146 <p>Within the class package, the methods will typically deal with the
147 reference as an ordinary reference. Outside the class package,
148 the reference is generally treated as an opaque value that may
149 be accessed only through the class's methods.</p>
150 <p>Although a constructor can in theory re-bless a referenced object
151 currently belonging to another class, this is almost certainly going
152 to get you into trouble. The new class is responsible for all
153 cleanup later. The previous blessing is forgotten, as an object
154 may belong to only one class at a time. (Although of course it's
155 free to inherit methods from many classes.) If you find yourself
156 having to do this, the parent class is probably misbehaving, though.</p>
157 <p>A clarification: Perl objects are blessed. References are not. Objects
158 know which package they belong to. References do not. The <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_bless"><code>bless()</code></a>
159 function uses the reference to find the object. Consider
160 the following example:</p>
161 <pre>
162 $a = {};
163 $b = $a;
164 bless $a, BLAH;
165 print &quot;\$b is a &quot;, ref($b), &quot;\n&quot;;</pre>
166 <p>This reports $b as being a BLAH, so obviously <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_bless"><code>bless()</code></a>
167 operated on the object and not on the reference.</p>
169 </p>
170 <h2><a name="a_class_is_simply_a_package_x_class__x_package__x__isa__x_inheritance_">A Class is Simply a Package
171 </a></h2>
172 <p>Unlike say C++, Perl doesn't provide any special syntax for class
173 definitions. You use a package as a class by putting method
174 definitions into the class.</p>
175 <p>There is a special array within each package called @ISA, which says
176 where else to look for a method if you can't find it in the current
177 package. This is how Perl implements inheritance. Each element of the
178 @ISA array is just the name of another package that happens to be a
179 class package. The classes are searched (depth first) for missing
180 methods in the order that they occur in @ISA. The classes accessible
181 through @ISA are known as base classes of the current class.</p>
182 <p>All classes implicitly inherit from class <code>UNIVERSAL</code> as their
183 last base class. Several commonly used methods are automatically
184 supplied in the UNIVERSAL class; see <a href="#default_universal_methods">Default UNIVERSAL methods</a> for
185 more details.
186 </p>
187 <p>If a missing method is found in a base class, it is cached
188 in the current class for efficiency. Changing @ISA or defining new
189 subroutines invalidates the cache and causes Perl to do the lookup again.</p>
190 <p>If neither the current class, its named base classes, nor the UNIVERSAL
191 class contains the requested method, these three places are searched
192 all over again, this time looking for a method named AUTOLOAD(). If an
193 AUTOLOAD is found, this method is called on behalf of the missing method,
194 setting the package global $AUTOLOAD to be the fully qualified name of
195 the method that was intended to be called.
196 </p>
197 <p>If none of that works, Perl finally gives up and complains.</p>
198 <p>If you want to stop the AUTOLOAD inheritance say simply
199 </p>
200 <pre>
201 sub AUTOLOAD;</pre>
202 <p>and the call will die using the name of the sub being called.</p>
203 <p>Perl classes do method inheritance only. Data inheritance is left up
204 to the class itself. By and large, this is not a problem in Perl,
205 because most classes model the attributes of their object using an
206 anonymous hash, which serves as its own little namespace to be carved up
207 by the various classes that might want to do something with the object.
208 The only problem with this is that you can't sure that you aren't using
209 a piece of the hash that isn't already used. A reasonable workaround
210 is to prepend your fieldname in the hash with the package name.
211 </p>
212 <pre>
213 sub bump {
214 my $self = shift;
215 $self-&gt;{ __PACKAGE__ . &quot;.count&quot;}++;
216 }</pre>
218 </p>
219 <h2><a name="a_method_is_simply_a_subroutine_x_method_">A Method is Simply a Subroutine
220 </a></h2>
221 <p>Unlike say C++, Perl doesn't provide any special syntax for method
222 definition. (It does provide a little syntax for method invocation
223 though. More on that later.) A method expects its first argument
224 to be the object (reference) or package (string) it is being invoked
225 on. There are two ways of calling methods, which we'll call class
226 methods and instance methods.</p>
227 <p>A class method expects a class name as the first argument. It
228 provides functionality for the class as a whole, not for any
229 individual object belonging to the class. Constructors are often
230 class methods, but see <a href="file://C|\msysgit\mingw\html/pod/perltoot.html">the perltoot manpage</a> and <a href="file://C|\msysgit\mingw\html/pod/perltooc.html">the perltooc manpage</a> for alternatives.
231 Many class methods simply ignore their first argument, because they
232 already know what package they're in and don't care what package
233 they were invoked via. (These aren't necessarily the same, because
234 class methods follow the inheritance tree just like ordinary instance
235 methods.) Another typical use for class methods is to look up an
236 object by name:</p>
237 <pre>
238 sub find {
239 my ($class, $name) = @_;
240 $objtable{$name};
241 }</pre>
242 <p>An instance method expects an object reference as its first argument.
243 Typically it shifts the first argument into a ``self'' or ``this'' variable,
244 and then uses that as an ordinary reference.</p>
245 <pre>
246 sub display {
247 my $self = shift;
248 my @keys = @_ ? @_ : sort keys %$self;
249 foreach $key (@keys) {
250 print &quot;\t$key =&gt; $self-&gt;{$key}\n&quot;;
252 }</pre>
254 </p>
255 <h2><a name="method_invocation_x_invocation__x_method__x_arrow__x_______">Method Invocation
256 &gt;&gt;</a></h2>
257 <p>For various historical and other reasons, Perl offers two equivalent
258 ways to write a method call. The simpler and more common way is to use
259 the arrow notation:</p>
260 <pre>
261 my $fred = Critter-&gt;find(&quot;Fred&quot;);
262 $fred-&gt;display(&quot;Height&quot;, &quot;Weight&quot;);</pre>
263 <p>You should already be familiar with the use of the <code>-&gt;</code> operator with
264 references. In fact, since <code>$fred</code> above is a reference to an object,
265 you could think of the method call as just another form of
266 dereferencing.</p>
267 <p>Whatever is on the left side of the arrow, whether a reference or a
268 class name, is passed to the method subroutine as its first argument.
269 So the above code is mostly equivalent to:</p>
270 <pre>
271 my $fred = Critter::find(&quot;Critter&quot;, &quot;Fred&quot;);
272 Critter::display($fred, &quot;Height&quot;, &quot;Weight&quot;);</pre>
273 <p>How does Perl know which package the subroutine is in? By looking at
274 the left side of the arrow, which must be either a package name or a
275 reference to an object, i.e. something that has been blessed to a
276 package. Either way, that's the package where Perl starts looking. If
277 that package has no subroutine with that name, Perl starts looking for
278 it in any base classes of that package, and so on.</p>
279 <p>If you need to, you <em>can</em> force Perl to start looking in some other package:</p>
280 <pre>
281 my $barney = MyCritter-&gt;Critter::find(&quot;Barney&quot;);
282 $barney-&gt;Critter::display(&quot;Height&quot;, &quot;Weight&quot;);</pre>
283 <p>Here <code>MyCritter</code> is presumably a subclass of <code>Critter</code> that defines
284 its own versions of <code>find()</code> and display(). We haven't specified what
285 those methods do, but that doesn't matter above since we've forced Perl
286 to start looking for the subroutines in <code>Critter</code>.</p>
287 <p>As a special case of the above, you may use the <code>SUPER</code> pseudo-class to
288 tell Perl to start looking for the method in the packages named in the
289 current class's <code>@ISA</code> list.
290 </p>
291 <pre>
292 package MyCritter;
293 use base 'Critter'; # sets @MyCritter::ISA = ('Critter');</pre>
294 <pre>
295 sub display {
296 my ($self, @args) = @_;
297 $self-&gt;SUPER::display(&quot;Name&quot;, @args);
298 }</pre>
299 <p>It is important to note that <code>SUPER</code> refers to the <code>superclass(es)</code> of the
300 <em>current package</em> and not to the <code>superclass(es)</code> of the object. Also, the
301 <code>SUPER</code> pseudo-class can only currently be used as a modifier to a method
302 name, but not in any of the other ways that class names are normally used,
304 </p>
305 <pre>
306 something-&gt;SUPER::method(...); # OK
307 SUPER::method(...); # WRONG
308 SUPER-&gt;method(...); # WRONG</pre>
309 <p>Instead of a class name or an object reference, you can also use any
310 expression that returns either of those on the left side of the arrow.
311 So the following statement is valid:</p>
312 <pre>
313 Critter-&gt;find(&quot;Fred&quot;)-&gt;display(&quot;Height&quot;, &quot;Weight&quot;);</pre>
314 <p>and so is the following:</p>
315 <pre>
316 my $fred = (reverse &quot;rettirC&quot;)-&gt;find(reverse &quot;derF&quot;);</pre>
317 <p>The right side of the arrow typically is the method name, but a simple
318 scalar variable containing either the method name or a subroutine
319 reference can also be used.</p>
321 </p>
322 <h2><a name="indirect_object_syntax_x_indirect_object_syntax__x_invocation__indirect__x_indirect_">Indirect Object Syntax
323 </a></h2>
324 <p>The other way to invoke a method is by using the so-called ``indirect
325 object'' notation. This syntax was available in Perl 4 long before
326 objects were introduced, and is still used with filehandles like this:</p>
327 <pre>
328 print STDERR &quot;help!!!\n&quot;;</pre>
329 <p>The same syntax can be used to call either object or class methods.</p>
330 <pre>
331 my $fred = find Critter &quot;Fred&quot;;
332 display $fred &quot;Height&quot;, &quot;Weight&quot;;</pre>
333 <p>Notice that there is no comma between the object or class name and the
334 parameters. This is how Perl can tell you want an indirect method call
335 instead of an ordinary subroutine call.</p>
336 <p>But what if there are no arguments? In that case, Perl must guess what
337 you want. Even worse, it must make that guess <em>at compile time</em>.
338 Usually Perl gets it right, but when it doesn't you get a function
339 call compiled as a method, or vice versa. This can introduce subtle bugs
340 that are hard to detect.</p>
341 <p>For example, a call to a method <code>new</code> in indirect notation -- as C++
342 programmers are wont to make -- can be miscompiled into a subroutine
343 call if there's already a <code>new</code> function in scope. You'd end up
344 calling the current package's <code>new</code> as a subroutine, rather than the
345 desired class's method. The compiler tries to cheat by remembering
346 bareword <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_require"><code>require</code></a>s, but the grief when it messes up just isn't worth the
347 years of debugging it will take you to track down such subtle bugs.</p>
348 <p>There is another problem with this syntax: the indirect object is
349 limited to a name, a scalar variable, or a block, because it would have
350 to do too much lookahead otherwise, just like any other postfix
351 dereference in the language. (These are the same quirky rules as are
352 used for the filehandle slot in functions like <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_print"><code>print</code></a> and <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_printf"><code>printf</code></a>.)
353 This can lead to horribly confusing precedence problems, as in these
354 next two lines:</p>
355 <pre>
356 move $obj-&gt;{FIELD}; # probably wrong!
357 move $ary[$i]; # probably wrong!</pre>
358 <p>Those actually parse as the very surprising:</p>
359 <pre>
360 $obj-&gt;move-&gt;{FIELD}; # Well, lookee here
361 $ary-&gt;move([$i]); # Didn't expect this one, eh?</pre>
362 <p>Rather than what you might have expected:</p>
363 <pre>
364 $obj-&gt;{FIELD}-&gt;move(); # You should be so lucky.
365 $ary[$i]-&gt;move; # Yeah, sure.</pre>
366 <p>To get the correct behavior with indirect object syntax, you would have
367 to use a block around the indirect object:</p>
368 <pre>
369 move {$obj-&gt;{FIELD}};
370 move {$ary[$i]};</pre>
371 <p>Even then, you still have the same potential problem if there happens to
372 be a function named <code>move</code> in the current package. <strong>The <code>-&gt;</code>
373 notation suffers from neither of these disturbing ambiguities, so we
374 recommend you use it exclusively.</strong> However, you may still end up having
375 to read code using the indirect object notation, so it's important to be
376 familiar with it.</p>
378 </p>
379 <h2><a name="default_universal_methods_x_universal_">Default UNIVERSAL methods
380 </a></h2>
381 <p>The <code>UNIVERSAL</code> package automatically contains the following methods that
382 are inherited by all other classes:</p>
383 <dl>
384 <dt><strong><a name="item_isa"><code>isa(CLASS)</code>
385 </a></strong>
387 <dd>
388 <p><a href="#item_isa"><code>isa</code></a> returns <em>true</em> if its object is blessed into a subclass of <code>CLASS</code></p>
389 </dd>
390 <dd>
391 <p>You can also call <code>UNIVERSAL::isa</code> as a subroutine with two arguments. Of
392 course, this will do the wrong thing if someone has overridden <a href="#item_isa"><code>isa</code></a> in a
393 class, so don't do it.</p>
394 </dd>
395 <dd>
396 <p>If you need to determine whether you've received a valid invocant, use the
397 <code>blessed</code> function from <a href="file://C|\msysgit\mingw\html/lib/Scalar/Util.html">the Scalar::Util manpage</a>:
398 </p>
399 </dd>
400 <dd>
401 <pre>
402 if (blessed($ref) &amp;&amp; $ref-&gt;isa( 'Some::Class')) {
403 # ...
404 }</pre>
405 </dd>
406 <dd>
407 <p><code>blessed</code> returns the name of the package the argument has been
408 blessed into, or <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_undef"><code>undef</code></a>.</p>
409 </dd>
410 </li>
411 <dt><strong><a name="item_can"><code>can(METHOD)</code>
412 </a></strong>
414 <dd>
415 <p><a href="#item_can"><code>can</code></a> checks to see if its object has a method called <code>METHOD</code>,
416 if it does then a reference to the sub is returned, if it does not then
417 <em>undef</em> is returned.</p>
418 </dd>
419 <dd>
420 <p><code>UNIVERSAL::can</code> can also be called as a subroutine with two arguments. It'll
421 always return <em>undef</em> if its first argument isn't an object or a class name.
422 The same caveats for calling <code>UNIVERSAL::isa</code> directly apply here, too.</p>
423 </dd>
424 </li>
425 <dt><strong><a name="item_version">VERSION( [NEED] )
426 </a></strong>
428 <dd>
429 <p><a href="#item_version"><code>VERSION</code></a> returns the version number of the class (package). If the
430 NEED argument is given then it will check that the current version (as
431 defined by the $VERSION variable in the given package) not less than
432 NEED; it will die if this is not the case. This method is normally
433 called as a class method. This method is called automatically by the
434 <a href="#item_version"><code>VERSION</code></a> form of <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_use"><code>use</code></a>.</p>
435 </dd>
436 <dd>
437 <pre>
438 use A 1.2 qw(some imported subs);
439 # implies:
440 A-&gt;VERSION(1.2);</pre>
441 </dd>
442 </li>
443 </dl>
444 <p><strong>NOTE:</strong> <a href="#item_can"><code>can</code></a> directly uses Perl's internal code for method lookup, and
445 <a href="#item_isa"><code>isa</code></a> uses a very similar method and cache-ing strategy. This may cause
446 strange effects if the Perl code dynamically changes @ISA in any package.</p>
447 <p>You may add other methods to the UNIVERSAL class via Perl or XS code.
448 You do not need to <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_use"><code>use UNIVERSAL</code></a> to make these methods
449 available to your program (and you should not do so).</p>
451 </p>
452 <h2><a name="destructors_x_destructor__x_destroy_">Destructors
453 </a></h2>
454 <p>When the last reference to an object goes away, the object is
455 automatically destroyed. (This may even be after you exit, if you've
456 stored references in global variables.) If you want to capture control
457 just before the object is freed, you may define a DESTROY method in
458 your class. It will automatically be called at the appropriate moment,
459 and you can do any extra cleanup you need to do. Perl passes a reference
460 to the object under destruction as the first (and only) argument. Beware
461 that the reference is a read-only value, and cannot be modified by
462 manipulating <code>$_[0]</code> within the destructor. The object itself (i.e.
463 the thingy the reference points to, namely <code>${$_[0]}</code>, <code>@{$_[0]}</code>,
464 <code>%{$_[0]}</code> etc.) is not similarly constrained.</p>
465 <p>Since DESTROY methods can be called at unpredictable times, it is
466 important that you localise any global variables that the method may
467 update. In particular, localise <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___"><code>$@</code></a> if you use <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_eval"><code>eval {}</code></a> and
468 localise <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item__"><code>$?</code></a> if you use <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_system"><code>system</code></a> or backticks.</p>
469 <p>If you arrange to re-bless the reference before the destructor returns,
470 perl will again call the DESTROY method for the re-blessed object after
471 the current one returns. This can be used for clean delegation of
472 object destruction, or for ensuring that destructors in the base classes
473 of your choosing get called. Explicitly calling DESTROY is also possible,
474 but is usually never needed.</p>
475 <p>Do not confuse the previous discussion with how objects <em>CONTAINED</em> in the current
476 one are destroyed. Such objects will be freed and destroyed automatically
477 when the current object is freed, provided no other references to them exist
478 elsewhere.</p>
480 </p>
481 <h2><a name="summary">Summary</a></h2>
482 <p>That's about all there is to it. Now you need just to go off and buy a
483 book about object-oriented design methodology, and bang your forehead
484 with it for the next six months or so.</p>
486 </p>
487 <h2><a name="twophased_garbage_collection_x_garbage_collection__x_gc__x_circular_reference__x_reference__circular__x_destroy__x_destructor_">Two-Phased Garbage Collection
489 </a></h2>
490 <p>For most purposes, Perl uses a fast and simple, reference-based
491 garbage collection system. That means there's an extra
492 dereference going on at some level, so if you haven't built
493 your Perl executable using your C compiler's <code>-O</code> flag, performance
494 will suffer. If you <em>have</em> built Perl with <code>cc -O</code>, then this
495 probably won't matter.</p>
496 <p>A more serious concern is that unreachable memory with a non-zero
497 reference count will not normally get freed. Therefore, this is a bad
498 idea:</p>
499 <pre>
501 my $a;
502 $a = \$a;
503 }</pre>
504 <p>Even thought $a <em>should</em> go away, it can't. When building recursive data
505 structures, you'll have to break the self-reference yourself explicitly
506 if you don't care to leak. For example, here's a self-referential
507 node such as one might use in a sophisticated tree structure:</p>
508 <pre>
509 sub new_node {
510 my $class = shift;
511 my $node = {};
512 $node-&gt;{LEFT} = $node-&gt;{RIGHT} = $node;
513 $node-&gt;{DATA} = [ @_ ];
514 return bless $node =&gt; $class;
515 }</pre>
516 <p>If you create nodes like that, they (currently) won't go away unless you
517 break their self reference yourself. (In other words, this is not to be
518 construed as a feature, and you shouldn't depend on it.)</p>
519 <p>Almost.</p>
520 <p>When an interpreter thread finally shuts down (usually when your program
521 exits), then a rather costly but complete mark-and-sweep style of garbage
522 collection is performed, and everything allocated by that thread gets
523 destroyed. This is essential to support Perl as an embedded or a
524 multithreadable language. For example, this program demonstrates Perl's
525 two-phased garbage collection:</p>
526 <pre>
527 #!/usr/bin/perl
528 package Subtle;</pre>
529 <pre>
530 sub new {
531 my $test;
532 $test = \$test;
533 warn &quot;CREATING &quot; . \$test;
534 return bless \$test;
535 }</pre>
536 <pre>
537 sub DESTROY {
538 my $self = shift;
539 warn &quot;DESTROYING $self&quot;;
540 }</pre>
541 <pre>
542 package main;</pre>
543 <pre>
544 warn &quot;starting program&quot;;
546 my $a = Subtle-&gt;new;
547 my $b = Subtle-&gt;new;
548 $$a = 0; # break selfref
549 warn &quot;leaving block&quot;;
550 }</pre>
551 <pre>
552 warn &quot;just exited block&quot;;
553 warn &quot;time to die...&quot;;
554 exit;</pre>
555 <p>When run as <em>/foo/test</em>, the following output is produced:</p>
556 <pre>
557 starting program at /foo/test line 18.
558 CREATING SCALAR(0x8e5b8) at /foo/test line 7.
559 CREATING SCALAR(0x8e57c) at /foo/test line 7.
560 leaving block at /foo/test line 23.
561 DESTROYING Subtle=SCALAR(0x8e5b8) at /foo/test line 13.
562 just exited block at /foo/test line 26.
563 time to die... at /foo/test line 27.
564 DESTROYING Subtle=SCALAR(0x8e57c) during global destruction.</pre>
565 <p>Notice that ``global destruction'' bit there? That's the thread
566 garbage collector reaching the unreachable.</p>
567 <p>Objects are always destructed, even when regular refs aren't. Objects
568 are destructed in a separate pass before ordinary refs just to
569 prevent object destructors from using refs that have been themselves
570 destructed. Plain refs are only garbage-collected if the destruct level
571 is greater than 0. You can test the higher levels of global destruction
572 by setting the PERL_DESTRUCT_LEVEL environment variable, presuming
573 <code>-DDEBUGGING</code> was enabled during perl build time.
574 See <a href="file://C|\msysgit\mingw\html/pod/perlhack.html#perl_destruct_level">PERL_DESTRUCT_LEVEL in the perlhack manpage</a> for more information.</p>
575 <p>A more complete garbage collection strategy will be implemented
576 at a future date.</p>
577 <p>In the meantime, the best solution is to create a non-recursive container
578 class that holds a pointer to the self-referential data structure.
579 Define a DESTROY method for the containing object's class that manually
580 breaks the circularities in the self-referential structure.</p>
582 </p>
583 <hr />
584 <h1><a name="see_also">SEE ALSO</a></h1>
585 <p>A kinder, gentler tutorial on object-oriented programming in Perl can
586 be found in <a href="file://C|\msysgit\mingw\html/pod/perltoot.html">the perltoot manpage</a>, <a href="file://C|\msysgit\mingw\html/pod/perlboot.html">the perlboot manpage</a> and <a href="file://C|\msysgit\mingw\html/pod/perltooc.html">the perltooc manpage</a>. You should
587 also check out <a href="file://C|\msysgit\mingw\html/pod/perlbot.html">the perlbot manpage</a> for other object tricks, traps, and tips, as
588 well as <a href="file://C|\msysgit\mingw\html/pod/perlmodlib.html">the perlmodlib manpage</a> for some style guides on constructing both
589 modules and classes.</p>
590 <table border="0" width="100%" cellspacing="0" cellpadding="3">
591 <tr><td class="block" style="background-color: #cccccc" valign="middle">
592 <big><strong><span class="block">&nbsp;perlobj - Perl objects</span></strong></big>
593 </td></tr>
594 </table>
596 </body>
598 </html>