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

The motivation behind this code is ... I recently learned of CoreList and thought this would be a simple way of determining whether or not I had a certain module installed (in this example, cgi).
#!perl use warnings; use strict; use Module::CoreList; my %modules = %{ $Module::CoreList::version{ 5.008 } }; while( %modules ) { if( keys %modules =~ /cgi/i ) { print "Found one!\n"; } }
Any ideas what's wrong with this? Thanks!

Replies are listed 'Best First'.
Re: CoreList stuff
by moritz (Cardinal) on Feb 01, 2009 at 22:05 UTC
    If you run the program, it tells you itself what's wrong:
    Applying pattern match (m//) to %hash will act on scalar(%hash) at foo +.pl line 10.

    What it tells you is that pattern matches generally act only on strings, not on lists or hashes.

    You could write your code as

    my %modules = %{ $Module::CoreList::version{ 5.008 } }; if( grep /cgi/i, keys %modules ) { print "Found one!\n"; }

    instead.

Re: CoreList stuff
by doom (Deacon) on Feb 01, 2009 at 22:02 UTC

    I think you misunderstood what Module::CoreList is for: it tells you about the "core" modules, i.e. the ones that are included by default with any distribution of perl. It's often useful to know when a paticular core module entered the core, if you're trying to support older versions of perl.

    A common way of finding out if you have a module is:

    perl -MSome::Module -e'print $Some::Module::VERSION, "\n"'
    If you get a version number, it's there, if not, you don't have it.

    From within perl code, I'd be inclined to require it and trap the error to find out if the require failed. Something like this:

    use Carp; my $module = "CGI"; eval "require $module"; if ($@) { carp "Problem with require of $module: $@"; } else { print "We have $module installed\n"; }

      Funny, I've been having trouble getting the version number of the module in the above code. This works, but I have a feeling there's a better way:
      use Carp; my $module = "CGI"; eval "require $module"; if ($@) { carp "Problem with require of $module: $@"; } else { { no strict "refs"; my $version = ${ $module. "::VERSION" }; print "We have $module installed, version: $version\n"; } }
        warn UNIVERSAL::VERSION($module); warn $module->VERSION;
Re: CoreList stuff
by toolic (Bishop) on Feb 01, 2009 at 22:09 UTC
    If you want to loop through all the keys of a hash, I think you want:
    for (keys %modules) { if (/cgi/i) { print "Found one $_\n" } }