in reply to Load all modules in directory

Use require instead of use and it might work (be sure to prepend the directory path, though).

----
I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
-- Schemer

: () { :|:& };:

Note: All code is untested, unless otherwise stated

Replies are listed 'Best First'.
Re: Re: Load all modules in directory
by ttcuberat (Sexton) on Dec 10, 2003 at 19:21 UTC
    I've tried all these things and just can't get the damn thing to work. Here is the latest version (which still fails miserably)

    BEGIN { $mod_path "/home/tboyd/lib/site_perl/5.6.1/Tools/"; my @mods = glob("$mod_path*"); for (@mods) { require $_; } }
    Again...my intention is to load all the .pm files in that directory at compile time. Any other thoughts?

      The code given has syntax errors in it, but setting those aside: It-Works-For-Me(tm). Here it is with typos removed:

      BEGIN { my $mod_path = "/home/tboyd/lib/site_perl/5.6.1/Tools/"; my @mods = glob("$mod_path*"); for (@mods) { require $_; } }

      It should be noted that require is different from use in that use calls the module's import method and require does not. So, this could cause problems later on if you expect symbols to be imported (or these modules do something else nice for you in import).

      You may also want to change your glob to end in *.pm if you only want those files as there could be other files in the directory that aren't perlish.

        For me, your code results in
        Can't locate C:/Perl/site/lib/ACME in @INC (@INC contains: C:/Perl/lib + C:/Perl/site/lib .) at C:\Dokumente und Einstellungen\foo\Desktop\t. +pl line 10. BEGIN failed--compilation aborted at C:\Dokumente und Einstellungen\fo +o\Desktop\t.pl line 12.
        I just tried to use eval to trap some nasty error messages and I got away with it -- I highly doubt whether this is legal, though:
        #!perl use strict; use warnings; BEGIN { my $dir = "C:/Perl/site/lib/"; my $r; for (<$dir*.pm>) { /([^\/]+)$/ && ($r = $1) or next; eval { rquire $_ } unless ($r and $INC{$r}); } } use Data::Dumper; print Dumper \%INC;

        Anyway, I hope this helped the OP.
        CombatSquirrel.
        Entropy is the tendency of everything going to hell.
      Would creating an "index" type module in that directory work? Or, is the list of modules too dynamic?

      It would be just a file Index.pm and look like this:

      require X; require Y; require Z;

      Unfortunately I don't have anywhere to test that right now.

      -Kurt

        I could do that, but the solution I'm looking for will allow me to put modules in the directory (i.e. a new module called Module4.pm) and then have the script automatically recognize the existence of this new mod. I'd like to have avoid the the maintence of an index.pm ;) -CUBErat