Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl pass object method reference as parameter to function

Tags:

methods

perl

i'm trying to do something like this:

-- source file 1

my $queue = Thread::Queue->new();
MyModules::populateQueue(<pass $queue->enqueue method reference);
...

-- package file

package MyModules

sub populateQueue {
  my $enqueue = $_[0];
  my $item = <find item to add to queue>;
  $enqueue->($item);

...

first, i'm not able to add "bless" to Thread::Queue

i've tried a couple of suggestions i found in stackoverflow:

my $enqueueRef = $queue->can('enqueue');
MyModules::populateQueue(\&enqueueRef); <--- fails in the package at line 

$enqueue->($item) with undefined subroutine

MyModules::populateQueue(\&queue->enqueue) <-- same failure as above

any idea how to pass a method of an object as a parameter to a function that can then be used in the function?

like image 972
schleprock Avatar asked Sep 19 '26 09:09

schleprock


1 Answers

Perl doesn't have a concept of a bound method reference. my $enqueue = $object->can('method') will return a code ref to a method if it exists, but the code ref isn't bound to that particular object – you still need to pass it as the first argument ($queue->$enqueue($item) or $enqueue->($queue, $item)).

To pass a bound method, the correct solution is to use an anonymous sub that wraps the method call:

populate_queue(sub { $queue->enqueue(@_) });
like image 140
amon Avatar answered Sep 22 '26 16:09

amon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!