Finding the packages in a required file

Simon Wistow simon at thegestalt.org
Sat May 24 14:47:39 BST 2014


I have a directory which looks like

  tmp/
    1.pl
    2.pl


1.pl looks like

  package Foo;

  sub hello { ... }

  1;


and 2.pl looks similar with a different (unique) package name.

Foo may be a subclass of a common class.

I'm trying to figure out a way to iterate through that directory and 
require each file and then get a list of all the packages. 

If I make all packages start with a common prefix (e.g package 
MyTest::Foo) then I can do

        opendir(my $dh, $dir) or die $!;
        while (my $file = readdir($dh)) {
                next if $file =~ /^\./;
                do(catfile($dir, $file));
        }
        closedir($dh);

        my $finder = Module::Pluggable::Object->new(
          search_dirs => "tmp/", 
          require     => 1, 
          search_path => "MyTest"
        );
        my @modules = $finder->plugins;

But I've been trying to figure out a way to make it work without the 
prefix. 

I can also do something like

    my @modules;
    opendir(my $dh, $dir) or die $!;
    while (my $file = readdir($dh)) {
            next if $file =~ /^\./;
            my $path = catfile($dir, $file); 
            require($path);
            push @modules, (read_file($path) =~ m!^package\s+([^\s+;]+)!msg);
    }
    closedir($dh);

But attempting to parse the file using regexes feels icky.

I thought about attempting to wrap package but I couldn't figure out how 
to do that using Hook::LexWrap, Class::Method::Modifiers or 
*CORE::GLOBAL::package = sub { ... } (which wouldn't be lexical anyway).

It's more than possible that's because I inexplicably woke up at 5am and 
I'm just being dumb.

Any suggestions, oh ye kind gentlefolk of this parish?




More information about the london.pm mailing list