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

Well, well, going towards expert programming :) Im was thinking if there is a nice way solving this:
Say I got this:
use strict; use warnings; my @addons; require "addon1.pl"; my $reg = \INIT(); push(@addons, $reg); require "addon2.pl"; $reg = \INIT(); push(@addons, $reg);
And, say "addon1.pl" looks like this:
sub INIT { my $name = shift; print "Hello, $name!"; }
Now, say I do:
$addons[0]->INIT("Jesus");
I want that to print:
Hello, Jesus!

Also, the implementation of INIT is supposed to be able of beeing different in different .pl "addons". Ideas?

UPDATE:
Thanks for input so far. Renamed INIT to something more personal. :)
Check this out:
package addon1; sub new { my $class = shift; my $self = []; return bless $self, $class; } sub ACE_INIT { shift; my $test = shift; $$test = "bar"; } return "addon1";
And:
my $pluginname = do "addon1.pl"; my $plugin = new $pluginname; my $test = "Foo..."; $plugin->ACE_INIT(\$test); print $test . "\n";
Maybe not totally perfect, but this works pretty fine...

Thanks,
Ace

Replies are listed 'Best First'.
Re: Doing "extensions"/"addons"
by merlyn (Sage) on Jul 29, 2005 at 02:08 UTC
    Well, you've got two problems that I see already. First,
    my $reg = \INIT();
    That takes a reference to the result obtained from invoking that subroutine right there, not a reference to the subroutine itself. If you want a chance of that working, you'll want my $reg = \&subroutinename instead. But, keep reading...

    Second, the name "INIT" is reserved. From perldoc perlmod:

    "INIT" blocks are run just before the Perl runtime begins execu +tion, in "first in, first out" (FIFO) order. For example, the code gener +ators documented in perlcc make use of "INIT" blocks to initialize an +d resolve pointers to XSUBs.

    -- Randal L. Schwartz, Perl hacker
    Be sure to read my standard disclaimer if this is a reply.

Re: Doing "extensions"/"addons"
by BUU (Prior) on Jul 29, 2005 at 02:05 UTC
    I'm a tad confused as to exactly what you're trying to do, but my $reg = \INIT(); is probably wrong. That takes a reference to the return value of INIT() (Which will probably be 1) instead of a reference to the subroutine named INIT. You want: my $ref = \&INIT;