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

greetings

I am trying to use dynamic class naming with something like:

BEGIN { $X="sargsSunOS_58"; } use vars qw(@a); use lib "/here/etc/packages"; use $X; @a=$X->new; print @a;
Is there anyway to do:

use $var
gratci

Replies are listed 'Best First'.
Re: dynamic class names
by particle (Vicar) on Jul 11, 2003 at 15:57 UTC

    from perldoc -f use:

    use Module VERSION LIST use Module VERSION use Module LIST use Module use VERSION Imports some semantics into the current package from the n +amed module, generally by aliasing certain subroutine or variab +le names into your package. It is exactly equivalent to BEGIN { require Module; import Module LIST; } except that Module *must* be a bareword.

    and from perldoc -f require:

    If EXPR is a bareword, the require assumes a ".pm" extensi +on and replaces "::" with "/" in the filename for you, to make it + easy to load standard modules. This form of loading of modules +does not risk altering your namespace. In other words, if you try this: require Foo::Bar; # a splendid bareword The require function will actually look for the "Foo/Bar.p +m" file in the directories specified in the @INC array. But if you try this: $class = 'Foo::Bar'; require $class; # $class is not a bareword #or require "Foo::Bar"; # not a bareword because of t +he "" The require function will look for the "Foo::Bar" file in +the @INC array and will complain about not finding "Foo::Bar" +there. In this case you can do: eval "require $class";

    so BEGIN{ my $var= 'CGI'; eval "require $var"; $var->import(); } should work.

    ~Particle *accelerates*

Re: dynamic class names
by dragonchild (Archbishop) on Jul 11, 2003 at 15:57 UTC
    The problem is use demands a string, not a variable. Try replacing the use line with:
    require "$X.pm"; $X->import;
    That is now a run-time directive (instead of use being a compile-time directive) so you don't need the BEGIN block anymore. :-)

    ------
    We are the carpenters and bricklayers of the Information Age.

    Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

    Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.

Re: dynamic class names
by hardburn (Abbot) on Jul 11, 2003 at 15:56 UTC

    You can do:

    BEGIN { $X = 'My::Module'; require $X; }

    But I can't remember how require does scoping.

    ----
    I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
    -- Schemer

    Note: All code is untested, unless otherwise stated