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