http://www.perlmonks.org?node_id=207508

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

Hi. Building a reporting system, a dashboard of metrics. One directory, /metrics, contains a host of modules that define and compute the metrics: Metric::Foo, Metric::Bar, Metric::Baz, etc. In many places I need to use all metrics, but I don't want to list them all out, as there are nearly 100 of them. What's the best way to do this? Thanks -- nop

Replies are listed 'Best First'.
Re: use (all)
by jmcnamara (Monsignor) on Oct 23, 2002 at 21:46 UTC

    The Module::Require module allows you to do this:
    use Module::Require 'require_regex'; require_regex('Metric::.*');

    From the pod:

    This module provides a way to load in a series of modules without having to know all the names, but just the pattern they fit. This can be useful for allowing drop-in modules for application expansion without requiring configuration or prior knowledge.

    --
    John.

Re: use (all)
by zigdon (Deacon) on Oct 23, 2002 at 19:57 UTC

    Perhaps autoload can help you avoid having to use them all always?. If not, how about this:

    opendir (DIR,"/path/to/dir") or die "Can't readdir: $!"; foreach my $module (grep /\.pm$/, readdir(DIR)) { require "/path/to/dir/$module"; $module =~ s/\.pm$//; import $module; } closedir DIR;

    I haven't tested this, so you might have to mess with the syntax to require and import.

    -- Dan

Re: use (all)
by rir (Vicar) on Oct 23, 2002 at 21:23 UTC
    The best thing would be to use a package that uses the packages you need.

    I'm likely to list all the files explicitly if they are all freestanding packages. I'd probably do this with my editor or code generator if practical.

    You also could:

    my @reqs = ( "Baz.pm", "Rot.pm" ); foreach (@reqs) { require; }
    But I think you want convenience not finer control.

    Update: Mispelling, grammar improvement.

any problems with:
by nop (Hermit) on Oct 23, 2002 at 21:29 UTC
    any problems with
    BEGIN {foreach (glob "$FindBin::Bin/metrics/*.pm") {require;}}
    ? I am thinking of taking this approach... anything that might bite me later? (I am not fluent in the nuances of use vs. require)
    nop