代码之家  ›  专栏  ›  技术社区  ›  SapphireSun

如何在perl中从部分命名空间动态发现包?

  •  0
  • SapphireSun  · 技术社区  · 15 年前

    我的目录结构如下:

    Foo::Bar::Baz::2等

    use Foo::Bar::Baz;

    谢谢!

    编辑:使模块更加清晰。

    4 回复  |  直到 15 年前
        1
  •  0
  •   DVK    15 年前

    要清楚的是,您是在看随机Perl代码中的随机包吗?

    模块 ,例如“a/b/c/d1.pm”和模块“a::b::c::d1”?

    在这两种情况下,都不能使用一个“use”语句来加载它们。

    您需要做的是使用 glob File::Find .

    在第一种情况下(模块),您可以通过 require s#/#::#g; s#\.pm$##; )打电话来 use 分别在每个模块上。

    对于嵌套在随机Perl文件中的实际包,这些包可以是:

    • 通过灰显每个文件列出(同样,通过 全球 文件::查找 /^package (.*);/

    • 通过执行 require $file 对于每个文件。

      在这种情况下,请注意 a/b/c/1.pl 不是

        2
  •  7
  •   friedo    15 年前

    如果要加载包含路径中具有特定前缀的所有模块(例如 a::b::c ,您可以使用 Module::Find .

    use Module::Find 'useall';
    
    my @loaded = useall 'Foo::Bar::Baz';  # loads everything under Foo::Bar::Baz
    

    这取决于你的年龄 @INC use lib )首先。

        3
  •  1
  •   Ether    15 年前

    main . 也许你在考虑 模块 使用诸如a/b/c.pm之类的名称(这是一个坏名称,因为小写的包名通常是为Perl内部保留的)。

    但是,给定一个目录路径,您可以查找 Perl模块使用 File::Find :

    use strict;
    use warnings;
    use File::Find;
    use Data::Dumper;
    
    my @modules;
    sub wanted
    {
        push @modules, $_ if m/\.pm$/
    }
    find(\&wanted, 'A/B');
    
    print "possible modules found:\n";
    print Dumper(\@modules)'
    
        4
  •  1
  •   mob    15 年前

    use strict; use warnings;
    my %original = map { $_ => 1 } get_namespaces("::");
    require Inline;
    print "New namespaces since 'require Inline' call are:\n";
    my @new_namespaces = sort grep !defined $original{$_}, get_namespaces("::");
    foreach my $new_namespace (@new_namespaces) {
      print "\t$new_namespace\n";
    }
    
    sub get_namespaces {
      # recursively inspect symbol table for known namespaces
      my $pkg = shift;
      my @namespace = ();
      my %s = eval "%" . $pkg;
      foreach my $key (grep /::$/, keys %s) {
        next if $key eq "main::";
        push @namespace, "$pkg$key", get_namespaces("$pkg$key");
      }
      return @namespace;
    }
    

    New namespaces since 'require Inline' call are:
            ::AutoLoader::
            ::Config::
            ::Digest::
            ::Digest::MD5::
            ::Dos::
            ::EPOC::
            ::Exporter::
            ::Exporter::Heavy::
            ::File::
            ::File::Spec::
            ::File::Spec::Cygwin::
            ::File::Spec::Unix::
            ::File::Spec::Win32::
            ::Inline::Files::
            ::Inline::denter::
            ::Scalar::
            ::Scalar::Util::
            ::Socket::
            ::VMS::
            ::VMS::Filespec::
            ::XSLoader::
            ::vars::
            ::warnings::register::
    
    推荐文章