in reply to Re: requiring pm modules
in thread requiring pm modules

First, i need to use 'require' because the 'Value.pm' comes from a configuration file. Secondly, i have declared at the top of my program:
use strict; no strict 'refs';
so no problem there either. :)

Replies are listed 'Best First'.
Re^3: requiring pm modules
by itub (Priest) on Nov 03, 2004 at 21:12 UTC
    Perhaps your code sample is too simplified and out of context, but I see absolutely no reason for using symbolic references. Heck, even within context I doubt it. I've written dozens of Perl modules and programs and haven't really needed symbolic references, except within the very limited context of exporting symbols or creating methods automatically (which doesn't seem to be the case here).

    Added 3 min later: if you don't know the name of the subroutine beforehand (and that's why you have it in $x), you can achieve a similar result without symbolic references by using object-oriented notation:

    require Value; $x = 'getValue'; Value->$x();

    Note that you'd have to change the getValue subroutine so that it shifts its first argument, which will hold the package name.

      Using the class method syntax will allow the symbolic reference even with strict, but it's still a symbolic reference. Instead, I would use can, as follows:

      require Value; my $x = 'getValue'; if (my $coderef = Value->can($x)) { $coderef->(); }

      This has several benefits. It does not add "Value" to the argument list, it does not use a symbolic reference, and it checks that the subroutine actually exists before trying to run it.

      PS: for the curious, can is documented in UNIVERSAL.

      The name of the function 'getValue' comes from the configuration file too. I guess I didn't have no any other way to implement it without using the symbolic reference. Michael
      The name of the function 'getValue' comes from the configuration file too and I guess I didn't know any other way to implement this. thanks, Michael
Re^3: requiring pm modules
by Mutant (Priest) on Nov 03, 2004 at 21:10 UTC
    If you really need to use a symbolic ref, you're probably better off doing something like:
    use strict; .. no strict 'refs'; $x = 'getValue'; &$x(); use strict 'refs';
    No need to turn off strict refs for the rest of your program.

      You could also use a bare block, so you don't have to remember to turn strict refs back on:

      use strict; ... { no strict 'refs'; $x = 'getValue'; &$x(); } # now we're back to strict refs

      But, personally, I would rather use can, as I explained in Re^4: requiring pm modules.