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

I have a code in Insert::Foo which is meant to run in each requirer's package:

# Insert/Foo.pm our $foo = 1; 1; # Client1.pm package Client1; require Insert::Foo; # $Client1::foo is set by Insert::Foo ... 1; # Client2.pm package Client2; require Insert::Foo; # $Client2::foo is set by Insert::Foo ... 1;

However, if I load Client2 and then Client3, Insert::Foo is not require'd again in Client3, because all modules are only loaded once. I can use do() instead of require(), but then I have to deal with filenames. I can manipulate %INC, but it feels hackish. Surely there's a proper mechanism for doing something like this?

Replies are listed 'Best First'.
Re: Require into package
by Anonymous Monk on Jan 21, 2011 at 03:31 UTC
    Surely there's a proper mechanism for doing something like this?

    import, Exporter

Re: Require into package
by tospo (Hermit) on Jan 21, 2011 at 14:47 UTC

    I think this is a design problem and that's why it feels hacky. Why do you set a global variable from a required package? Instead, I would give Insert::Foo a function/method to return whatever $foo needs to be (perhaps this is set according to some config?) and use that to set a local variable in the clients.

Re: Require into package
by nif (Sexton) on Jan 21, 2011 at 14:33 UTC

    Here is an example

    File Foo.pm:

    package Foo; use strict; use warnings; use Exporter; our @ISA = qw(Exporter); our $foo = "FOO"; our @EXPORT = qw( $foo ); 1;
    File Client1.pm:
    package Client1; use strict; use warnings; use Foo; 1;
    File Client2.pm:
    package Client2; use strict; use warnings; use Foo; 1;
    File main.pl
    #!/usr/bin/perl use strict; use warnings; use Client1; use Client2; print "Client1::foo=", $Client1::foo, "\n"; print "Client2::foo=", $Client2::foo, "\n"; #both variables $Client1::foo and $Client2::foo are just other names f +or $Foo::foo, #so the second assignment wins $Client1::foo = 'CLIENT1'; $Client2::foo = 'CLIENT2'; print "Client1::foo=", $Client1::foo, "\n"; print "Client2::foo=", $Client2::foo, "\n";
    Program output:
    Client1::foo=FOO Client2::foo=FOO Client1::foo=CLIENT2 Client2::foo=CLIENT2
    I'm actually not sure that this is what you really want to do. Please provide some more details if it is not.