in reply to Packagename as a variable?

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";

Replies are listed 'Best First'.
Re: Re: Packagename as a variable?
by joe (Acolyte) on Nov 23, 2000 at 04:01 UTC
    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.