Hi Monks,
I want to write a module which provides users both of functional interface and object-oriented one.
# OO interface
use Foo;
my $o = Foo->new();
$o->method1();
$o->method2();
# Functional interface
use Foo qw(method1_foo method2_foo);
method1_foo();
method2_foo();
To implement above features, I wrote the following code:
# Foo.pm
package Foo;
use Exporter 'import';
our @EXPORT_OK = qw(method1_foo method2_foo);
sub new {
return Foo::Object->new(
method1 => sub { shift; method1_foo(@_) },
method2 => sub { shift; method2_foo(@_) },
);
}
sub method1_foo {
# do method1
}
sub method2_foo {
# do method2
}
package Foo::Object;
sub new {
my ( $class, %method ) = @_;
# adds methods
while ( my ( $method, $code_ref ) = each %method ) {
next if ref $code_ref ne 'CODE';
my $slot = __PACKAGE__ . "::$method";
{
no strict 'refs';
*$slot = $code_ref;
}
}
return bless \do { my $anon_scalar }, $class;
}
1;
I'm afraid that my way seems bad practice.
I referred to CPAN modules like
Object::Prototype.
In this case, I think it's not appropriate to use this module. (I can't explain why not appropriate)
Although there are many ways to implement above features,
it's difficult to choose one of them.
Help me, Monks!
-
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.