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";
}
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|