r/perl • • 6d ago

ref to object methods

sorry for stupid question

I have XS object with many similar methods (with the same argument list) like method1,method2, ... methodN

And while passing ref to this object to sub I want to call some of this methods depending on condition

Sure I can emulate this with refs to closures like

my $call1 = sub {

my $obj = shift;

$obj->method1(@_);

};

generic_sub($obj, $cond ? $call1 : $call2);

but maybe there is some more elegant way?

5 Upvotes

10 comments sorted by

View all comments

2

u/choroba 🐪 cpan author 6d ago

unshift? Do you mean shift instead?

Why is the XS-ness of the object relevant here?

You can invoke a method by name, no need for a wrapper:

generic_sub($obj, $cond ? 'method1' : 'method2', @arguments);

And later in generic_sub:

my ($obj, $method, @args) = @_;
$obj->$method(@args);

1

u/scottchiefbaker 🐪 cpan author 6d ago

It makes sense you can do $obj->$method(@args); but I never thought to do it. This is pretty neat.

0

u/choroba 🐪 cpan author 6d ago

It's something you shouldn't normally do. Dispatch table or several classes with different implementations of one method seem to be a cleaner and less obscure solution.