source: trunk/essentials/dev-lang/perl/pod/perlobj.pod@ 3609

Last change on this file since 3609 was 3181, checked in by bird, 19 years ago

perl 5.8.8

File size: 21.6 KB
Line 
1=head1 NAME
2X<object> X<OOP>
3
4perlobj - Perl objects
5
6=head1 DESCRIPTION
7
8First you need to understand what references are in Perl.
9See L<perlref> for that. Second, if you still find the following
10reference work too complicated, a tutorial on object-oriented programming
11in Perl can be found in L<perltoot> and L<perltooc>.
12
13If you're still with us, then
14here are three very simple definitions that you should find reassuring.
15
16=over 4
17
18=item 1.
19
20An object is simply a reference that happens to know which class it
21belongs to.
22
23=item 2.
24
25A class is simply a package that happens to provide methods to deal
26with object references.
27
28=item 3.
29
30A method is simply a subroutine that expects an object reference (or
31a package name, for class methods) as the first argument.
32
33=back
34
35We'll cover these points now in more depth.
36
37=head2 An Object is Simply a Reference
38X<object> X<bless> X<constructor> X<new>
39
40Unlike say C++, Perl doesn't provide any special syntax for
41constructors. A constructor is merely a subroutine that returns a
42reference to something "blessed" into a class, generally the
43class that the subroutine is defined in. Here is a typical
44constructor:
45
46 package Critter;
47 sub new { bless {} }
48
49That word C<new> isn't special. You could have written
50a construct this way, too:
51
52 package Critter;
53 sub spawn { bless {} }
54
55This might even be preferable, because the C++ programmers won't
56be tricked into thinking that C<new> works in Perl as it does in C++.
57It doesn't. We recommend that you name your constructors whatever
58makes sense in the context of the problem you're solving. For example,
59constructors in the Tk extension to Perl are named after the widgets
60they create.
61
62One thing that's different about Perl constructors compared with those in
63C++ is that in Perl, they have to allocate their own memory. (The other
64things is that they don't automatically call overridden base-class
65constructors.) The C<{}> allocates an anonymous hash containing no