[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Omaha.pm] Chaining a method (called "init")




On Sep 23, 2005, at 1:58 AM, Brian Wiese wrote:
I'm a bit out of touch with my perl syntax, could your explain this with
some comments?

Sure, I'll try. The gist is that I've got a deep object hierarchy.

A is the base class of B. B is the base class of C, etc to E.

When I instantiate an E and call init(), I'm expecting the A init to run, then the B init, then the C init, etc.

So the code below just demostrates that.

Jay Hannah wrote:
This is just a sanity check that chaining methods works the way I
thought it did.

---------------------------
$ cat j.pl
#!/usr/bin/perl

use vars qw( @ISA );

package A;
sub new {
 # I really don't understand this mojo,
 # but we know it works when we use it...
 my ($caller) = (@_);
 my $caller_is_obj = ref($caller);
 my $class = $caller_is_obj || $caller;
 my $self = bless {}, ref($class) || $class;
}
sub init { print "a"; }

That was it for A. new() is inherited by all subclasses.

package B;
@ISA = ('A');
sub init { $_[0]->SUPER::init; print "b"; }

And that's all there is to each child. Each child just declares its parent and then polymorph's the init() method, running it's parent's init() first, then printing its own letter.

C, D, E are the same as B:

package C;
@ISA = ('B');
sub init { $_[0]->SUPER::init; print "c"; }

package D;
@ISA = ('C');
sub init { $_[0]->SUPER::init; print "d"; }

package E;
@ISA = ('D');
sub init { $_[0]->SUPER::init; print "e"; }

Then we write our "main" routine -- it's where the code starts running.

package main;

Instatiate an E:

my $obj = E->new;

Print a line of debug just to make sure that I do, indeed have an E now:

print "\$obj is $obj\n";

Then run init and see if it does what I expected/wanted. Plus a newline.

$obj->init;
print "\n";

That's it. When I run the program it does what I expected:

---------------------------

Yup. It does what I expected:
---------------------------
$ perl j.pl
$obj is E=HASH(0x815c088)
abcde
---------------------------

Is that what you were looking for?

I hope that helped,

j