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

I suppose you rather mean
my $collection = Collection->new({ 'sorter' => \&Sort::mysorter }); sub new { my ($self, $options) = @_; . . . $self->{sorter} = $options->{sorter}; }
As to my knowledge, this should work (notice the slash - backslash difference).
Cheers, CombatSquirrel.

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:04 UTC
    To all who noted the backslash, I have the correct slash direction in my real code. The code I posted was typed in lovingly by hand into the web page since I can't cut and paste between the computer I develop on (Sparcstation) and the one I Monk on (Windows). It doesn't seem to matter whether I use the form:
    my $collection = Collection->new({ 'sorter' => Sort::mysorter }); sub new { my ($self, $options) = @_; . . . $self->{sorter} = \&$options->{sorter}; }
    or...
    my $collection = Collection->new({ 'sorter' => \&Sort::mysorter }); sub new { my ($self, $options) = @_; . . . $self->{sorter} = $options->{sorter}; }
    When I get to :
    $self->sorter($stuffToSort);
    or $self->sorter->($stuffToSort); I get the same results.

    DrSax

      here it is in separate files works fine:

      [bobn@trc2:/home/bobn/misc]# cat subref.pl #!/usr/bin/perl -w use lib q/./; use Collection; use Sort; my $collection = Collection->new({ 'sorter' => \&Sort::mysorter }); $collection->doit('here is something'); [bobn@trc2:/home/bobn/misc]# cat Collection.pm package Collection; my $self = {}; sub new { my ($class, $options) = @_; $self->{sorter} = $options->{sorter}; bless $self, $class; } sub doit { my ($self, $stuffToSort ) = @_; print "in doit: $stuffToSort\n"; $self->{sorter}->($stuffToSort); print "in doit: $stuffToSort\n"; } 1; [bobn@trc2:/home/bobn/misc]# cat Sort.pm package Sort; sub mysorter { print "in mysorter, @_\n"; } 1; [bobn@trc2:/home/bobn/misc]# ./subref.pl in doit: here is something in mysorter, here is something in doit: here is something

      All code given here is UNTESTED unless otherwise stated.

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