anazawa has asked for the wisdom of the Perl Monks concerning the following question:
Hi Monks,
I want to write a module which provides users both of functional interface and object-oriented one.To implement above features, I wrote the following code:# 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();
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)# 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;
Although there are many ways to implement above features, it's difficult to choose one of them. Help me, Monks!
|
---|
Back to
Seekers of Perl Wisdom