-1

I want to call a method on a package name generated from a variable. I think I've done this before but it appears I have forgotten how. Here's the broken version of what I'm trying to achieve.

my $var = 'Page';
my $p = My::Package::$var->new();
StevieD
  • 6,925
  • 2
  • 25
  • 45
  • You *reallý* don't want to do this. – Borodin Sep 30 '17 at 17:28
  • Why? What is the issue with it? – StevieD Sep 30 '17 at 17:33
  • Take a look at the duplicate question, and read [*Why it's stupid to "use a variable as a variable name"*](https://perl.plover.com/varvarname.html) especially Part II. – Borodin Sep 30 '17 at 17:49
  • 1
    I just read them and they don't seem to apply to my situation. Thanks, though. – StevieD Sep 30 '17 at 17:54
  • It's less critical when you're using class names, but it's best not to split a class name up into bits, which are mostly a reflection of their file structure on disk. You can write `my $class = 'My::Package::Page'` and `my $p = $class->new`. (You can even write `my $var = 'Page'` and `my $p = "My::Package::$var"->new` but that's horrible.) But now you have an object `$p` whose methods you don't know without checking its class. – Borodin Sep 30 '17 at 18:05

1 Answers1

0

I was able to get this working using answer at Perl, dynamically include package

my $module_name = 'Some::Module';
(my $require_name = $module_name . ".pm") =~ s{::}{/}g;
require $require_name;
my $obj = $module_name->new();
StevieD
  • 6,925
  • 2
  • 25
  • 45
  • This answer doesn't match the question! But since you claim it's a duplicate of the other question, I'll oblige and close your question. – ikegami Sep 30 '17 at 21:02