in reply to Passing a reference to a subroutine in a constructor

After making '/' a '\', it works for me:

my $collection = Collection->new({ 'sorter' => Sort::mysorter }); $collection->doit; package Collection; sub new { my ($class, $options) = @_; $self->{sorter} = \&{$options->{sorter}}; bless {}, $class; } sub doit { print "iam doit\n"; $self->{sorter}->($mystuffToSort); } package Sort; sub mysorter { print "iam mysorter\n"; }

On the other hand, I'm not sure what you meant by "out of the scope of the calling package".

All code given here is UNTESTED unless otherwise stated.

--Bob Niederman, http://bob-n.com

Replies are listed 'Best First'.
Re: Re: Passing a reference to a subroutine in a constructor
by DrSax (Sexton) on Aug 22, 2003 at 19:09 UTC
    Your approach only seems to work for me when the package is in the same file. All of our classes/packages live in seperate files. Could that have an impact?

    DrSax

      Just wondering: have you actually -use-d or -require-d the other packages?

      I realize this is equivalent to asking whether the computer is plugged in, but you never know ;-)

      Liz

        Yes. I have "use Sort" (or its real equivalent) in the package.

        I wish that I could supply it dynamically in my code without the class having to know about it, though..."

        DrSax