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

I have a project where a start-up script forks N sub scripts which do various pieces of work. Each of these instantiates 1-M modules depending on the type of work each has to do. I have some code for getting MySQL connections that I want to share between the various pieces. At the moment the sub is in a module along with the code for instantiating the separate modules.

I want to pass a reference to the connection sub into each module as it gets created. I can get the reference using the '\&sub' notation but I can't seem to get it made available to the new module.

########### snip eval( require( 'Parser/' . $parser_name . '.pm')); $self->{ 'parser' }->{ $parser_name } = $parser_name->new(); ####This is the problematic line: $self->{ 'parser' }->{ $parser_name }->getDBH = \&getDBH;

What syntax do I use for this?

PS yes - this does need to be re-engineered into a class hierarchy. That will probably occur later this year.

Replies are listed 'Best First'.
Re: sub by reference - assigning to an object?
by Fletch (Bishop) on Mar 26, 2008 at 15:51 UTC

    You're trying to assign to a method, which isn't going to work without some deep magic (and even then that's probably not what you want to do). You really want the subref to either be passed as a parameter to the constructor ($parser_name->new( getDBH => \&getDBH )) and/or stored in an attribute ($self->{ 'getDBH_sub' } = \&getDBH) and then the parser instances use that to call the proper routine that way.

    Update: So to elaborate, basically each parser class' getDBH routine would look something like this:

    sub getDBH { my $self = shift; my $getDBH_ref = $self->{ 'getDBH_sub' }; $getDBH_ref->( ); }

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

      What if I want to do something like:

      my $common = common_class->new(); my $parser = parser_class->new(); ### this is the ugly part $parser->{ 'getDBH' } = \&$common->getDBH;

      In my original code this is more like what I was attempting.
        If getDBH() doesn't actually depend on $common and it's state you could do
        $parser->{ 'getDBH' } = \&common_class::getDBH;
        otherwise you could store a wrapper to the getDBH() invocation:
        $parser->{ 'getDBH' } = sub { $common->getDBH; };
Re: sub by reference - assigning to an object?
by ysth (Canon) on Mar 26, 2008 at 15:53 UTC
    Without knowing what $self->{parser}{$parser_name} is, it's hard to say, but maybe $self->{ 'parser' }->{ $parser_name }->getDBH(\&getDBH); would work?

    Also, your parsers could just call the original getDBH sub fully qualified, like $dbh = main::getDBH(...).