in reply to Perl OO: switch package context.

ovid once wrote a module to do that: aliased.

Otherwise: it's possible to have Class be a constant, in your package, with value "My::Package::Class". that ought to work too. Well, in my tests, it does. :)

package My::Package; use constant Class => __PACKAGE__ . '::Class'; print ref Class->new; # prints "My::Package::Class" { package My::Package::Class; sub new { return bless {}, shift; } }

Replies are listed 'Best First'.
Re^2: Perl OO: switch package context.
by sorhed (Acolyte) on May 15, 2005 at 13:03 UTC

    OK, that works indeed. But (oh, I know it is cruel) I need to do that at runtime, within eval context.

    So:

    use aliased Foo::Bar::Object; print ref Object->new();

    works, so works this one:

    use constant Object => 'Foo::Bar::Object'; print ref Object->new();

    But eval'ing this stuff does not:

    eval 'use aliased Gemini::Model::Object;'; print ref Object->new();

    or:

    eval qq[use constant Object => 'Foo::Bar::Object';]; print ref Object->new();
    What's wrong with that? :)
      It's too late at runtime, the rest of the script already got compiled. So "Object" is taken as a bareword string literal, and nothing can change that.

      As a constant is nothing but a sub, you can use a similar sub that just returns the value of a scalar. You can always change the value for the scalar.

      my $class = "Gemini::Model::Object"; sub Object () { return $class; } print ref Object->new();
      You can always still change the value of that scalar.

      But why the obfuscation? If you want to use a variable class, just say so. Perl lets you do that.

      my $class = "Gemini::Model::Object"; print ref $class->new();
      Looks fine to me.