Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

It seems that if I set a coderef equal to a reference to a subroutine in the current package and then pass it to a routine from another package when I try to call it from that package it craps out. If I pass it an anonymous sub it works fine. Can anyone clue me into the difference between these two methods or any work arounds to this problem?

Thanks in advance,

Ben

Replies are listed 'Best First'.
Re (tilly) 1: Question about coderefs
by tilly (Archbishop) on Apr 12, 2001 at 08:26 UTC
    Code would help.

    At a guess your reference to a subroutine in the current package is a string naming the subroutine, in which case you are doing a symbolic lookup. That breaks when the lookup is done in another package. The simplest way to check that is through use strict, which will catch the error up front rather than through allowing subtle bugs in your code and understanding survive. That said, here is a working example:

    package Foo; use strict; # Always sub foo { (shift)->(); # Call the function passed in by reference } package Bar; sub bar { print "This is bar\n"; } Foo::foo(\&bar); # Pass a ref to a sub to another package
    Note that I am explicitly creating the reference, as perlref says to, using a \. And it works.
Re: Question about coderefs
by ton (Friar) on Apr 12, 2001 at 07:19 UTC
    Ben,

    generally, it's a good idea to post the code that you're using along with your question. It's possible that the problem is somewhere other than where you think it is.

    Also, lots of us are lazy, and really don't want to write code to test what you want us to test. Debugging existing code is another matter entirely... :)

    -Ton

    -----

    Be bloody, bold, and resolute; laugh to scorn
    The power of man...