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

Hello again perlmonks!
I'm wondering how I would accomplish this;
$x = "joe"; package $x; #do lots of stuff in joe:: package main; # stuff in main::
I tried assigning $x in a BEGIN block, but that didn't work either. All I get is:
syntax error at ./junk.pl line 6, near "package $x"
please tell me it's doable! :-)
Thanks and happy birthday merlyn!!

Replies are listed 'Best First'.
Re: Packagename as a variable?
by rpc (Monk) on Nov 23, 2000 at 03:56 UTC
    Wrap it in an eval:
    #!/usr/bin/perl -w use strict; my $pkgname = "Foobar"; eval qq{ package $pkgname; print "lots of stuff.\n"; }; package main; print "more stuff.\n";
      Thanks. Yes that will work, but it'll be way ugly... lots of escaping to do. I also, have numerous places in the code that I would like to use the package $var construct, so evals everywhere.
      If it is the only solution, then it is probably what I will do.
      thanks.
        What I'm always curious about is
        what is the problem that you're solving, that you think that part of the solution is "I need a variable package name, so how do I do that?"
        Because if you've gotten to that as part of your solution, I think you're solving the wrong problem. Can you say more about the problem you're trying to solve?

        -- Randal L. Schwartz, Perl hacker

        Hmm, this might be a way to make it more convienant.
        #!/usr/bin/perl -w package Namespace; use strict; # bless the namespace into our module sub new { my($class, $pkgname) = @_; bless \$pkgname, ref($class) || $class; } # wrap some code into our namespace sub do { my($self) = shift; my $code = join "", @_; eval qq{ package $$self; $code; }; if($@) { print "eval failed: $@\n"; } } 1; package main; my $n = new Namespace("foo"); $n->do( q{ $a = 666; print "$a\n"; print "a lot of stuff.\n"; } );
        This way, you could wrap large chunks of code with q{} and not have to worry about escaping characters.