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

I would like to require a module version and print the version used to a logfile. But when I try to do it as shown, I get an error saying sub ok() is undefined. The sub ok() works fine if I don't quote and eval it.
use strict; use diagnostics; my $var = ' use SANDY 1.5; use SANDY qw(ok); '; eval($var); print $var; ok();

Replies are listed 'Best First'.
Re: $VERSION to logfile?
by jmcnamara (Monsignor) on Apr 16, 2003 at 08:08 UTC

    Here is a small program that "requires" a list of modules and prints their versions. It only works for modules that have $VERSION defined:
    #!/usr/bin/perl -w use strict; my @modules = qw( File::Copy File::Find File::Foo File::Spec File::Temp ); for my $module (@modules) { my $version; eval "require $module"; if (not $@) { $version = $module->VERSION; $version = '(unknown)' if not defined $version; } else { $version = '(not installed)'; } print $module, "\t", $version, "\n"; } __END__ Prints: File::Copy 2.03 File::Find (unknown) File::Foo (not installed) File::Spec 0.82 File::Temp 0.12

    In your example you should check the $@ variable, see perlvar, after using eval to see if there was as error:

    print "Eval error: ", $@ if $@;

    --
    John.

      This works great (I have chaged it to require my modules that are only found in the same directory as my script). One question, if I change
      eval "require $module";
      to require $module; it fails because it looks only in @INC rather than in the same directory as my script . Why is eval needed to get it to look in the directory?