in reply to Refactoring a module with many anonymous subrefs as an OO module

Not really sure if this will help in your case, but here's a little trick with coderefs that many people don't know about.

#!/usr/bin/perl use strict; use warnings; { package Foo; sub new { bless {} => shift } sub name { return 'telcontar' } } my $method = sub { return shift->name }; print Foo->new->$method;

That should print 'telcontar'. In other words, you can call your coderefs as methods on your object and the first argument in @_ will be your object, as expected.

Update: that changes your code to this:

sub access { my ( $self, $x, $y ) = splice @_, 0, 3; my $method = $self->{crefs}{$x}{$y}; return $self->$method(@_); }

Cheers,
Ovid

New address of my CGI Course.

Replies are listed 'Best First'.
Re^2: Refactoring a module with many anonymous subrefs as an OO module
by telcontar (Beadle) on Nov 21, 2007 at 13:32 UTC
    Wow, that's exactly what I was missing - I did NOT know that!

    In my case, the anonymous subs are part of package Foo. So to provide some sort of interface and access them from outside the package, is this the best way?
    #!/usr/bin/perl use strict; use warnings; { package Foo; our %HASH; $HASH{blah} = sub { my $self = shift; print $self->{value}; }; sub new { bless { crefs => \%HASH, value => 'telcontar' } => shift + } sub access { my $self = shift; my $coderef = $self->{crefs}{+shift}; $self->$coderef(@_) } } my $x = Foo->new; $x->access('blah');
    Thanks!
    -- telcontar

      That's certainly better than the 1,1 you were passing earlier. You could also iterate over the hash and build up accessors.

      while ( my ( $name, $code ) = each %hash ) { no strict 'refs'; *$name = $code; }

      And then you could just call:

      $x->blah;

      That provides a couple of advantages. First, you don't have to remember to check if the key in the hash exists (as I forgot to do in my example to you). Second, you can gain a limited bit of introspection:

      if ( my $method = $x->can('blah') ) { $x->$method; }

      However, beyond your example, I don't really know what your needs are, so this may not work for you.

      Cheers,
      Ovid

      New address of my CGI Course.

        Thanks a lot. You were of immense help.

        -- telcontar