I have a plain old module that I wrote before I was conversant with Perl OO.
It provides a several subroutines, which I call from many scripts, built up over several years.
At present, I want to morph my module to OO (so that each instance can have a state which is accessible to all subs).
However, I want to morph the module in a such way that my old scripts continue to work, and that my new scripts can use the OO syntax and other goodies. I found one way to do this, shown below on a very simple example.
Learned monks, I would like to see your comments on other, perhaps better ways to achieve my goal.
#! perl -w
use strict;
package MyModule;
sub isFile {
my $file = shift; # a file in local directory expected
my $verbose = shift; # optional
if (! -f $file) {
print STDERR "*** no such file $file in current directory\n";
return 0;
}
else {
print STDERR "... isFile $file\n" if $verbose;
return 1;
}
}
# more subs ...
1;
A test script, before the change
#! perl -w
use strict;
use MyModule;
# before change to OO and after
MyModule::isFile("MyModuleTest.pl");
MyModule::isFile("NotHere");
MyModule after the change
#! perl -w
use strict;
package MyModule;
sub new {
my ($class, %args) = @_;
my $self = {
class => $class,
verbose => $args{verbose} || 0,
otheropt => $args{otheropt} || 0,
};
bless $self, $class;
return $self;
}
sub isFile {
my $self = shift if ref $_[0] && ref $_[0] eq $_[0]->{class};
my $file = shift; # a file in current directory expected
if (! -f $file) {
print STDERR "*** $file: file not found in current directory\n
+";
return 0;
}
else {
print STDERR "... $file: file found in current directory\n" if
+ $self->{verbose};
return 1;
}
}
# more subs ...
1;
A test script, after the change
#! perl -w
use strict;
use MyModule;
# works before change to OO and after
MyModule::isFile("MyModuleTest.pl");
MyModule::isFile("NotHere");
# works after change to OO
my $mod = MyModule->new;
$mod->isFile("MyModuleTest.pl");
$mod->isFile("NotHere");
$mod = MyModule->new( verbose => 1 );
$mod->isFile("MyModuleTest.pl");
$mod->isFile("NotHere");
rudif