in reply to Call sub in variable module

G'day tel2,

The documentation for require explains how to achieve this. See the text, about half-way down, near:

eval "require $class";

Update: Sorry, I appear to have missed the last line of your post:

"Also, if each module will always contain only 1 sub, do they need to have a sub at all? If not, how can they be written & called without a sub?"

That's not addressed in the require documentation.

Actually, I don't understand what you're asking here which appears to be "How to call a sub that doesn't exist?". Please elaborate.

— Ken

Replies are listed 'Best First'.
Re^2: Call sub in variable module
by tel2 (Pilgrim) on Nov 07, 2016 at 01:54 UTC
    Thanks Ken,

    I have recently read that area of that "require" webpage, but I couldn't see anything which answered my question, i.e. "how can I call mysub() now?", and I still can't now.
    Could you please copy/paste the exact sentence that answers that question?

    Regarding the 2nd part of my question, i.e.:
    "Also, if each module will always contain only 1 sub, do they need to have a sub at all? If not, how can they be written & called without a sub?"
    , I was just about to remove it from my original question when you (with lightning speed which proves you must be just across the ditch, mate) responded.  I've removed it now, because it's not really related, and might ask it again as a separate question someday.  Meanwhile, let's (virtually) sweep that one under the carpet.

    Thanks.

      Once you've done the

      eval "require $class";

      part, you just need

      $class->mysub();

      to call it. Here's a working example.

      Module './pm_1175392/mymod123.pm':

      package pm_1175392::mymod123; sub mysub { return 'In package: ' . __PACKAGE__; } 1;

      Script './pm_1175392_variable_name_mod.pl':

      #!/usr/bin/env perl -l use strict; use warnings; my $modno = '123'; my $class = "pm_1175392::mymod$modno"; eval "require $class"; print $class->mysub();

      Sample run:

      $ ./pm_1175392_variable_name_mod.pl In package: pm_1175392::mymod123 $

      The require documentation has information on the eval part. See "perlobj: Invoking Class Methods" for information on the calling part.

      Regarding the bit now "under the carpet", please don't do that. It's better to <strike> such text so that subsequent posts still make sense (all explained here). And, yes, I am "just across the ditch" :-)

      — Ken

        I'm with ya now, Ken.
        And it works!
        Thanks for your help.
        And I've reinstated/stuck-out my previously deleted text, as requested.
        tel2