home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 2 / AACD 2.iso / AACD / Programming / perlman / man / perlobj.txt < prev    next >
Encoding:
Text File  |  1999-09-09  |  16.4 KB  |  434 lines

  1. NAME
  2.        perlobj - Perl objects
  3.  
  4. DESCRIPTION
  5.        First of all, you need to understand what references are
  6.        in Perl.  See the perlref manpage for that.
  7.  
  8.        Here are three very simple definitions that you should
  9.        find reassuring.
  10.  
  11.        1.  An object is simply a reference that happens to know
  12.            which class it belongs to.
  13.  
  14.        2.  A class is simply a package that happens to provide
  15.            methods to deal with object references.
  16.  
  17.        3.  A method is simply a subroutine that expects an object
  18.            reference (or a package name, for static methods) as
  19.            the first argument.
  20.  
  21.        We'll cover these points now in more depth.
  22.  
  23.        An Object is Simply a Reference
  24.  
  25.        Unlike say C++, Perl doesn't provide any special syntax
  26.        for constructors.  A constructor is merely a subroutine
  27.        that returns a reference to something "blessed" into a
  28.        class, generally the class that the subroutine is defined
  29.        in.  Here is a typical constructor:
  30.  
  31.            package Critter;
  32.            sub new { bless {} }
  33.  
  34.        The {} constructs a reference to an anonymous hash
  35.        containing no key/value pairs.  The bless() takes that
  36.        reference and tells the object it references that it's now
  37.        a Critter, and returns the reference.  This is for
  38.        convenience, since the referenced object itself knows that
  39.        it has been blessed, and its reference to it could have
  40.        been returned directly, like this:
  41.  
  42.            sub new {
  43.                my $self = {};
  44.                bless $self;
  45.                return $self;
  46.            }
  47.  
  48.        In fact, you often see such a thing in more complicated
  49.        constructors that wish to call methods in the class as
  50.        part of the construction:
  51.  
  52.            sub new {
  53.                my $self = {}
  54.                bless $self;
  55.                $self->initialize();
  56.                return $self;
  57.            }
  58.  
  59.        If you care about inheritance (and you should; see
  60.        L<perlmod/"Modules: Creation, Use and Abuse">), then you
  61.        want to use the two-arg form of bless so that your
  62.        constructors may be inherited:
  63.  
  64.            sub new {
  65.                my $class = shift;
  66.                my $self = {};
  67.                bless $self, $class
  68.                $self->initialize();
  69.                return $self;
  70.            }
  71.  
  72.        Or if you expect people to call not just CLASS->new() but
  73.        also $obj->new(), then use something like this.  The
  74.        initialize() method used will be of whatever $class we
  75.        blessed the object into:
  76.  
  77.            sub new {
  78.                my $this = shift;
  79.                my $class = ref($this) || $this;
  80.                my $self = {};
  81.                bless $self, $class
  82.                $self->initialize();
  83.                return $self;
  84.            }
  85.  
  86.        Within the class package, the methods will typically deal
  87.        with the reference as an ordinary reference.  Outside the
  88.        class package, the reference is generally treated as an
  89.        opaque value that may only be accessed through the class's
  90.        methods.
  91.  
  92.        A constructor may re-bless a referenced object currently
  93.        belonging to another class, but then the new class is
  94.        responsible for all cleanup later.  The previous blessing
  95.        is forgotten, as an object may only belong to one class at
  96.        a time.  (Although of course it's free to inherit methods
  97.        from many classes.)
  98.  
  99.        A clarification:  Perl objects are blessed.  References
  100.        are not.  Objects know which package they belong to.
  101.        References do not.  The bless() function simply uses the
  102.        reference in order to find the object.  Consider the
  103.        following example:
  104.  
  105.            $a = {};
  106.            $b = $a;
  107.            bless $a, BLAH;
  108.            print "\$b is a ", ref($b), "\n";
  109.  
  110.        This reports $b as being a BLAH, so obviously bless()
  111.        operated on the object and not on the reference.
  112.  
  113.        A Class is Simply a Package
  114.  
  115.        Unlike say C++, Perl doesn't provide any special syntax
  116.        for class definitions.  You just use a package as a class
  117.        by putting method definitions into the class.
  118.  
  119.        There is a special array within each package called @ISA
  120.        which says where else to look for a method if you can't
  121.        find it in the current package.  This is how Perl
  122.        implements inheritance.  Each element of the @ISA array is
  123.        just the name of another package that happens to be a
  124.        class package.  The classes are searched (depth first) for
  125.        missing methods in the order that they occur in @ISA.  The
  126.        classes accessible through @ISA are known as base classes
  127.        of the current class.
  128.  
  129.        If a missing method is found in one of the base classes,
  130.        it is cached in the current class for efficiency.
  131.        Changing @ISA or defining new subroutines invalidates the
  132.        cache and causes Perl to do the lookup again.
  133.  
  134.        If a method isn't found, but an AUTOLOAD routine is found,
  135.        then that is called on behalf of the missing method.
  136.  
  137.        If neither a method nor an AUTOLOAD routine is found in
  138.        @ISA, then one last try is made for the method (or an
  139.        AUTOLOAD routine) in a class called UNIVERSAL.  If that
  140.        doesn't work, Perl finally gives up and complains.
  141.  
  142.        Perl classes only do method inheritance.  Data inheritance
  143.        is left up to the class itself.  By and large, this is not
  144.        a problem in Perl, because most classes model the
  145.        attributes of their object using an anonymous hash, which
  146.        serves as its own little namespace to be carved up by the
  147.        various classes that might want to do something with the
  148.        object.
  149.  
  150.        A Method is Simply a Subroutine
  151.  
  152.        Unlike say C++, Perl doesn't provide any special syntax
  153.        for method definition.  (It does provide a little syntax
  154.        for method invocation though.  More on that later.)  A
  155.        method expects its first argument to be the object or
  156.        package it is being invoked on.  There are just two types
  157.        of methods, which we'll call static and virtual, in honor
  158.        of the two C++ method types they most closely resemble.
  159.        A static method expects a class name as the first
  160.        argument.  It provides functionality for the class as a
  161.        whole, not for any individual object belonging to the
  162.        class.  Constructors are typically static methods.  Many
  163.        static methods simply ignore their first argument, since
  164.        they already know what package they're in, and don't care
  165.        what package they were invoked via.  (These aren't
  166.        necessarily the same, since static methods follow the
  167.        inheritance tree just like ordinary virtual methods.)
  168.        Another typical use for static methods is to look up an
  169.        object by name:
  170.  
  171.            sub find {
  172.                my ($class, $name) = @_;
  173.                $objtable{$name};
  174.            }
  175.  
  176.        A virtual method expects an object reference as its first
  177.        argument.  Typically it shifts the first argument into a
  178.        "self" or "this" variable, and then uses that as an
  179.        ordinary reference.
  180.  
  181.            sub display {
  182.                my $self = shift;
  183.                my @keys = @_ ? @_ : sort keys %$self;
  184.                foreach $key (@keys) {
  185.                    print "\t$key => $self->{$key}\n";
  186.                }
  187.            }
  188.  
  189.        Method Invocation
  190.  
  191.        There are two ways to invoke a method, one of which you're
  192.        already familiar with, and the other of which will look
  193.        familiar.  Perl 4 already had an "indirect object" syntax
  194.        that you use when you say
  195.  
  196.            print STDERR "help!!!\n";
  197.  
  198.        This same syntax can be used to call either static or
  199.        virtual methods.  We'll use the two methods defined above,
  200.        the static method to lookup an object reference and the
  201.        virtual method to print out its attributes.
  202.  
  203.            $fred = find Critter "Fred";
  204.            display $fred 'Height', 'Weight';
  205.  
  206.        These could be combined into one statement by using a
  207.        BLOCK in the indirect object slot:
  208.  
  209.            display {find Critter "Fred"} 'Height', 'Weight';
  210.  
  211.        For C++ fans, there's also a syntax using -> notation that
  212.        does exactly the same thing.  The parentheses are required
  213.        if there are any arguments.
  214.  
  215.            $fred = Critter->find("Fred");
  216.            $fred->display('Height', 'Weight');
  217.  
  218.        or in one statement,
  219.  
  220.            Critter->find("Fred")->display('Height', 'Weight');
  221.  
  222.        There are times when one syntax is more readable, and
  223.        times when the other syntax is more readable.  The
  224.        indirect object syntax is less cluttered, but it has the
  225.        same ambiguity as ordinary list operators.  Indirect
  226.        object method calls are parsed using the same rule as list
  227.        operators: "If it looks like a function, it is a
  228.        function".  (Presuming for the moment that you think two
  229.        words in a row can look like a function name.  C++
  230.        programmers seem to think so with some regularity,
  231.        especially when the first word is "new".)  Thus, the
  232.        parens of
  233.  
  234.            new Critter ('Barney', 1.5, 70)
  235.  
  236.        are assumed to surround ALL the arguments of the method
  237.        call, regardless of what comes after.  Saying
  238.  
  239.            new Critter ('Bam' x 2), 1.4, 45
  240.  
  241.        would be equivalent to
  242.  
  243.            Critter->new('Bam' x 2), 1.4, 45
  244.  
  245.        which is unlikely to do what you want.
  246.  
  247.        There are times when you wish to specify which class's
  248.        method to use.  In this case, you can call your method as
  249.        an ordinary subroutine call, being sure to pass the
  250.        requisite first argument explicitly:
  251.  
  252.            $fred =  MyCritter::find("Critter", "Fred");
  253.            MyCritter::display($fred, 'Height', 'Weight');
  254.  
  255.        Note however, that this does not do any inheritance.  If
  256.        you merely wish to specify that Perl should START looking
  257.        for a method in a particular package, use an ordinary
  258.        method call, but qualify the method name with the package
  259.        like this:
  260.  
  261.            $fred = Critter->MyCritter::find("Fred");
  262.            $fred->MyCritter::display('Height', 'Weight');
  263.  
  264.        If you're trying to control where the method search begins
  265.        and you're executing in the class itself, then you may use
  266.        the SUPER pseudoclass, which says to start looking in your
  267.        base class's @ISA list without having to explicitly name
  268.        it:
  269.  
  270.            $self->SUPER::display('Height', 'Weight');
  271.  
  272.        Please note that the SUPER:: construct is only meaningful
  273.        within the class.
  274.  
  275.        Sometimes you want to call a method when you don't know
  276.        the method name ahead of time.  You can use the arrow
  277.        form, replacing the method name with a simple scalar
  278.        variable containing the method name:
  279.  
  280.            $method = $fast ? "findfirst" : "findbest";
  281.            $fred->$method(@args);
  282.  
  283.        Destructors
  284.  
  285.        When the last reference to an object goes away, the object
  286.        is automatically destroyed.  (This may even be after you
  287.        exit, if you've stored references in global variables.)
  288.        If you want to capture control just before the object is
  289.        freed, you may define a DESTROY method in your class.  It
  290.        will automatically be called at the appropriate moment,
  291.        and you can do any extra cleanup you need to do.
  292.  
  293.        Perl doesn't do nested destruction for you.  If your
  294.        constructor reblessed a reference from one of your base
  295.        classes, your DESTROY may need to call DESTROY for any
  296.        base classes that need it.  But this only applies to
  297.        reblessed objects--an object reference that is merely
  298.        CONTAINED in the current object will be freed and
  299.        destroyed automatically when the current object is freed.
  300.  
  301.        WARNING
  302.  
  303.        An indirect object is limited to a name, a scalar
  304.        variable, or a block, because it would have to do too much
  305.        lookahead otherwise, just like any other postfix
  306.        dereference in the language.  The left side of -> is not
  307.        so limited, because it's an infix operator, not a postfix
  308.        operator.
  309.  
  310.        That means that below, A and B are equivalent to each
  311.        other, and C and D are equivalent, but AB and CD are
  312.        different:
  313.  
  314.            A: method $obref->{"fieldname"}
  315.            B: (method $obref)->{"fieldname"}
  316.            C: $obref->{"fieldname"}->method()
  317.            D: method {$obref->{"fieldname"}}
  318.  
  319.        Summary
  320.  
  321.        That's about all there is to it.  Now you just need to go
  322.        off and buy a book about object-oriented design
  323.        methodology, and bang your forehead with it for the next
  324.        six months or so.
  325.  
  326.        Two-Phased Garbage Collection
  327.  
  328.        For most purposes, Perl uses a fast and simple reference-
  329.        based garbage collection system.  For this reason, there's
  330.        an extra dereference going on at some level, so if you
  331.        haven't built your Perl executable using your C compiler's
  332.        -O flag, performance will suffer.  If you have built Perl
  333.        with cc -O, then this probably won't matter.
  334.  
  335.        A more serious concern is that unreachable memory with a
  336.        non-zero reference count will not normally get freed.
  337.        Therefore, this is a bad idea:
  338.  
  339.            {
  340.                my $a;
  341.                $a = \$a;
  342.            }
  343.  
  344.        Even thought $a should go away, it can't.  When building
  345.        recursive data structures, you'll have to break the self-
  346.        reference yourself explicitly if you don't care to leak.
  347.        For example, here's a self-referential node such as one
  348.        might use in a sophisticated tree structure:
  349.  
  350.            sub new_node {
  351.                my $self = shift;
  352.                my $class = ref($self) || $self;
  353.                my $node = {};
  354.                $node->{LEFT} = $node->{RIGHT} = $node;
  355.                $node->{DATA} = [ @_ ];
  356.                return bless $node => $class;
  357.            }
  358.  
  359.        If you create nodes like that, they (currently) won't go
  360.        away unless you break their self reference yourself.  (In
  361.        other words, this is not to be construed as a feature, and
  362.        you shouldn't depend on it.)
  363.  
  364.        Almost.
  365.  
  366.        When an interpreter thread finally shuts down (usually
  367.        when your program exits), then a rather costly but
  368.        complete mark-and-sweep style of garbage collection is
  369.        performed, and everything allocated by that thread gets
  370.        destroyed.  This is essential to support Perl as an
  371.        embedded or a multithreadable language.  For example, this
  372.        program demonstrates Perl's two-phased garbage collection:
  373.            #!/usr/bin/perl
  374.            package Subtle;
  375.  
  376.            sub new {
  377.                my $test;
  378.                $test = \$test;
  379.                warn "CREATING " . \$test;
  380.                return bless \$test;
  381.            }
  382.  
  383.            sub DESTROY {
  384.                my $self = shift;
  385.                warn "DESTROYING $self";
  386.            }
  387.  
  388.            package main;
  389.  
  390.            warn "starting program";
  391.            {
  392.                my $a = Subtle->new;
  393.                my $b = Subtle->new;
  394.                $$a = 0;  # break selfref
  395.                warn "leaving block";
  396.            }
  397.  
  398.            warn "just exited block";
  399.            warn "time to die...";
  400.            exit;
  401.  
  402.        When run as /tmp/test, the following output is produced:
  403.  
  404.            starting program at /tmp/test line 18.
  405.            CREATING SCALAR(0x8e5b8) at /tmp/test line 7.
  406.            CREATING SCALAR(0x8e57c) at /tmp/test line 7.
  407.            leaving block at /tmp/test line 23.
  408.            DESTROYING Subtle=SCALAR(0x8e5b8) at /tmp/test line 13.
  409.            just exited block at /tmp/test line 26.
  410.            time to die... at /tmp/test line 27.
  411.            DESTROYING Subtle=SCALAR(0x8e57c) during global destruction.
  412.  
  413.        Notice that "global destruction" bit there?  That's the
  414.        thread garbage collector reaching the unreachable.
  415.  
  416.        Objects are always destructed, even when regular refs
  417.        aren't and in fact are destructed in a separate pass
  418.        before ordinary refs just to try to prevent object
  419.        destructors from using refs that have been themselves
  420.        destructed.  Plain refs are only garbage collected if the
  421.        destruct level is greater than 0.  You can test the higher
  422.        levels of global destruction by setting the
  423.        PERL_DESTRUCT_LEVEL environment variable, presuming
  424.        -DDEBUGGING was enabled during perl build time.
  425.  
  426.        A more complete garbage collection strategy will be
  427.        implemented at a future date.
  428.  
  429. SEE ALSO
  430.        You should also check out the perlbot manpage for other
  431.        object tricks, traps, and tips, as well as the perlmod
  432.        manpage for some style guides on constructing both modules
  433.        and classes.
  434.