Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams
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?

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(@_) });
                just to add clarity, i did the following in the MyModules package: MyModules::populateQueue(sub {$queue->enqueue(@_)}); which works.
– schleprock
                Nov 2, 2017 at 17:53
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.