in reply to Dynamic USE and %INC

BEGIN { my $varName = 'SOME_VAR'; my $varValue = 123; ## ## Dynamically create the package ## my $code = qq/ package Somepackage; use Exporter; our \@ISA = qw(Exporter); our \@EXPORT_OK = qw(\$$varName); our \$$varName = $varValue; 1; /; print $code, "\n"; eval $code; $INC{"Somepackage.pm"} = 'abc'; }

eval(STRING) should be a tool of last resort - it should certainly come after symrefs on your list of things to try.

BEGIN { my $varName = 'SOME_VAR'; my $varValue = 123; require Exporter; $INC{"Somepackage.pm"} = 1; package Somepackage; our @ISA = qw(Exporter); our @EXPORT_OK = $varName; no strict 'refs'; $$varName = $varValue; }

Replies are listed 'Best First'.
Re^2: Dynamic USE and %INC
by Bas-i (Initiate) on Mar 17, 2005 at 21:52 UTC
    Care to explain why I wouldn't want to use eval in this case?

    The example doesn't show but I use eval's result to see if all went well (the variable names and values come from a db that might have garbage in them, causing compilation errors).

    Then again, your example could be nested in an eval {} block as well to check for this.

      Care to explain why I wouldn't want to use eval in this case?

      Mostly it's instinct. Using eval mixes up program space a dataspace even more than symrefs. Where there are two solutions of equal complexity one using eval(STRING) and the other not then use the one without.

      The other nasty thing about eval is that unless you use a #line directive the errors you get just say "in eval 666" or something equally unhelpful.

      The example doesn't show but I use eval's result to see if all went well (the variable names and values come from a db that might have garbage in them, causing compilation errors).
      But if you didn't constuct a string as pass it to the compiler then there wouldn't be any errors! Why should garbage in the values cause errors? As it happens garbage in the names won't throw any errors either since symbols defined with symrefs can have any name.

      Anyhow if the database is not trusted to be valid you definitely should not be passing it to eval() in case it decides to reformat your disk.

      You are praising eval(STRING) because it provides you with a solution that it caused.

      With my solution all you need to add is a check that $varName !~ /\W/. Actually if there's a chance that the database is truely malicious and not just erroneous then you really should check $varName is not null or one of the special globally global variables.

      $varName && $varName !~ /\W/ && \*$varName != \*{"::$varName"}