Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: How to morph a plain module to OO

by blssu (Pilgrim)
on Sep 08, 2002 at 00:06 UTC ( [id://195939]=note: print w/replies, xml ) Need Help??


in reply to How to morph a plain module to OO

Perl OO is a lot more flexible than most people are used to. Two self-imposed beliefs are tripping you up. First, you can have more than one package in a module. Second, you don't need to bless your object to the package the constructor is defined in.

Here's a clean version of your example written with two packages -- the original module with function call API and the new "improved" module with the object API. The constructor for the object API is defined in the old module so the actual class name of your new object API is hidden from the user. (Users don't need to change their require statements and can slowly adopt the OO API.)

## MyModule.pm first package MyModule; use strict; sub isFile { my($file, $verbose) = @_; print "checking file '$file': " if ($verbose); if (! -f $file) { print "not found\n" if ($verbose); return 0; } else { print "found\n" if ($verbose); return 1; } } sub new { my $class = shift; my %self = @_; return bless \%self, $class . 'OO'; } package MyModuleOO; use strict; sub isFile { my($self, $file, $verbose) = @_; $verbose = $self->{verbose} unless (defined $verbose); MyModule::isFile($file, $verbose); } sub verboseOff { my($self) = @_; $self->{verbose} = 0; } 1; ## t.pl usage test use strict; use MyModule; if (MyModule::isFile('MyModule.pm', 1)) { print "ok\n"; } my $env = MyModule->new(verbose => 1); if ($env->isFile('MyModule.pm')) { print "ok\n"; } $env->verboseOff; if ($env->isFile('MyModule.pm')) { print "ok\n"; }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://195939]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (3)
As of 2024-04-25 22:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found