3

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?

2
  • 2
    just wrap it around sub: sub { $queue->enqueue; } Commented Nov 2, 2017 at 14:52
  • There's also the curry module on CPAN. Commented Nov 2, 2017 at 15:06

1 Answer 1

8

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(@_) });
Sign up to request clarification or add additional context in comments.

1 Comment

just to add clarity, i did the following in the MyModules package: MyModules::populateQueue(sub {$queue->enqueue(@_)}); which works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.