<?xml version="1.0" encoding="windows-1252"?>
<node id="954299" title="Module provides both of functional interface and object-oriented one" created="2012-02-16 12:44:16" updated="2012-02-16 12:44:16">
<type id="115">
perlquestion</type>
<author id="954280">
anazawa</author>
<data>
<field name="doctext">
&lt;p&gt;Hi Monks,&lt;/p&gt;

I want to write a module which provides users both of functional interface and object-oriented one.

&lt;code&gt;
# OO interface
use Foo;
my $o = Foo-&gt;new();
$o-&gt;method1();
$o-&gt;method2();

# Functional interface
use Foo qw(method1_foo method2_foo);
method1_foo();
method2_foo();
&lt;/code&gt;

To implement above features, I wrote the following code:

&lt;code&gt;
# Foo.pm
package Foo;
use Exporter 'import';

our @EXPORT_OK = qw(method1_foo method2_foo);

sub new {
    return Foo::Object-&gt;new(
        method1 =&gt; sub { shift; method1_foo(@_) },
        method2 =&gt; 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;
&lt;/code&gt;

I'm afraid that my way seems bad practice.
I referred to CPAN modules like [mod://Object::Prototype].
In this case, I think it's not appropriate to use this module. (I can't explain why not appropriate)

&lt;p&gt;Although there are many ways to implement above features,
it's difficult to choose one of them.
Help me, Monks!&lt;p&gt;</field>
</data>
</node>
