belden has asked for the wisdom of the Perl Monks concerning the following question:
One of the things that I've been bitten by in my test programs is that my low-level package has the object constructor, not the high-level package. The 'bite' is that sometimes I forget, and instead of typing
my $tool = LowUtils->new ( file => 'foo' )
I type
my $tool = Utils->new ( file => 'foo' )
Today I realized that in the high-level package I can just add a new method which calls the low-level package's new method. Here's some sample code to show what I ended up doing:
Output:#!/usr/bin/perl BEGIN { use strict; use warnings; } package Utils; sub new { # discard my class... shift(@_); # ...and invoke LowUtils::new as though # it were called by our caller. LowUtils::new ( 'LowUtils', @_ ); } sub get_numlines { my $self = shift; return scalar @{$self->{FILEDATA}}; } sub DESTROY { print "\tthis is the Utils destructor\n"; } 1; # end package Utils package LowUtils; @LowUtils::ISA = qw ( Utils ) ; sub new { my $proto= shift(@_); my %args= @_; my $class = ref($proto) || $proto; my $self = {}; $self->{FILENAME} = $args{file}; $self->{FILEDATA} = []; bless $self, $class; $self->init; return $self; } sub init { my $self= shift(@_); my %args= @_; open DAT, $self->{FILENAME} or return undef; @{$self->{FILEDATA}} = <DAT>; close DAT; return $self; } sub DESTROY { print "\tthis is the LowUtils destructor\n"; } 1; # end package LowUtils my $utils = Utils->new ( file => $0 ); print 'Utils: lines = ', $utils->get_numlines, "\n"; undef $utils; my $low = LowUtils->new ( file => $0 ); print 'LowUtils: lines = ', $low->get_numlines, "\n"; undef $low; exit;
Utils: lines = 72
this is the LowUtils destructor
LowUtils: lines = 72
this is the LowUtils destructor
I arrived at this solution after deciding that it probably wouldn't be smart to set @Utils::ISA to refer back to LowUtils. My questions:
blyman
setenv EXINIT 'set noai ts=2'
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Faking new() method in high-level package
by jreades (Friar) on May 08, 2002 at 21:54 UTC | |
by belden (Friar) on May 08, 2002 at 22:38 UTC | |
by jreades (Friar) on May 08, 2002 at 23:13 UTC | |
by belden (Friar) on May 09, 2002 at 00:05 UTC |