in reply to Encapsulation and Subroutine redefined warnings

Here is a super-simple OO framework for you.

Processor.pm

package Processor; # constructor in base class only sub new { my $pkg = shift; bless {}, $pkg; } # init, process, finish in subclasses 1;

Processor/SomeSubClass.pm

package Processor::SomeSubClass; @ISA = ( Processor ); sub init { my $self = shift; # do something } # should be called process_line # this one upcases it sub process { my $self = shift; my $line = shift; return uc( $line ); } sub finish { my $self = shift; # do something } 1;

The script that runs it:

#!/usr/bin/perl use Processor; use Processor::SomeSubClass; my $p = Processor::SomeSubClass->new(); $p->init; while (<>) { print $p->process( $_ ); } $p->finish;

I'm not totally sure if this is what you intended - init and finish coming before and after processing all the lines for example - but it should get you going if you havent't done it before.

Note that my examlpe does not store any of the data in the object - again, because its hard to see what problem you are going to be solving.

qq

Replies are listed 'Best First'.
Re: Re: Encapsulation and Subroutine redefined warnings
by jspeaks (Novice) on Nov 25, 2003 at 16:46 UTC
    qq,

    Thanks for taking to time to provide that framework. That is what I was looking for to my overall design question. The one other question I have is about self determination of all the available processors. I planned on doing something similar to the following code, but I need to determine the base class versus just matching on the name of the object:
    foreach $symname (sort keys %main::) { #print "$_\n" if /^ybcp/; if ( $symname =~ /^ybcp/ ) { local *sym = $main::{$symname}; $$sym->init(); #print "\$$symname\n" if defined $sym; } }
    With loops like this in my driver script, I should be able to simply add a new use statement for new processors.

    Also... Just to wrap up my thoughts on my original issue. I was confused by my Perl book's explanation of the Exporter implementation. I thought it was necessary to add methods to the Exporter to make them accessible, but I now realize that it meant accessible without the module:: syntax.

      If you want to loop over a list of subclassed processors, you probably want something like:

      use Processor; use Processor::SomeSubClass; use Processor::AnotherSubClass; foreach ( qw( SomeSubClass AnotherSubClass ) ) { my $pkg = "Processor::$_"; my $processor = $pkg->new(); $processor->init(); # do something with $processor }

      Damien Conway's book is very good on OO perl, although he skips fast past some of the simple stuff.

      qq