in reply to How not to hardcode a package name?

I can't count the number of times that this question has bugged me in my own coding! It seems that there should be some CPAN module that does this, analogous to UNIVERSAL::require, which lets you require a module whose name is in a variable.

While I know that it wouldn't be elegant, isn't there an eval-based way to do this? I tried the simple-minded
my $a = 'Package'; eval "package $a";,
but it doesn't work (I suspect because I don't really understand the eval EXPR form).

Replies are listed 'Best First'.
Re^2: How not to hardcode a package name?
by ikegami (Patriarch) on Aug 28, 2008 at 20:28 UTC

    The package of a line of code is set when that line is compiled.

    Furthermore, package is lexically scoped, so you can't just put the eval in a BEGIN.

    You can do

    my $p = 'Package'; my $c = 'print(__PACKAGE__);'; # Some code eval "package $a; $c";
      Thanks! Does this:
      The package of a line of code is set when that line is compiled.

      Furthermore, package is lexically scoped, so you can't just put the eval in a BEGIN.

      mean that it can't be done, or just that an eval is not the way to do it? (If I understand your code snippet correctly, you're saying that I can build up all the code I want in that package into a single string and eval that—but I'm sure that's not Best Practice, to say the least.)

        Does this mean that it can't be done

        I showed one way of doing it. It could also be done using source filters. It might even be possible to do it after the fact by poking at the internals. And of course, you could patch your Perl to get the effect you want.

        Whether or not those methods are worthwhile depends on the situation.

Re^2: How not to hardcode a package name?
by blazar (Canon) on Aug 28, 2008 at 22:45 UTC