码神之路:Perl篇

Mojo::Loader

2017-10-10  本文已影响5人  JSON_NULL

简介

use Mojo::Loader qw(data_section find_modules load_class);

# Find modules in a namespace
for my $module (find_modules 'Some::Namespace') {

  # Load them safely
  my $e = load_class $module;
  warn qq{Loading "$module" failed: $e} and next if ref $e;

  # And extract files from the DATA section
  say data_section($module, 'some_file.txt');
}

Mojo :: Loader是一个类加载器,同时也是一个插件框架。除了查找模块和加载类之外,它还允许将多个文件存储在包的DATA段中,然后可以使用Mojo::Loader单独访问。

package Foo;

1;
__DATA__

@@ test.txt
This is the first file.

@@ test2.html (base64)
VGhpcyBpcyB0aGUgc2Vjb25kIGZpbGUu

@@ test
This is the
third file.

在上面的代码中,__DATA__段中的内容是三个SECTION,每个SECTION有一个以@@作为起始字符的标题开头。在@@后面紧跟的是SECTION的名称和用于解码其内容的可选指令。对于解码内容的指令目前仅支持Base64,Bases4编码可以方便于存储二进制数据的存储。

方法

Mojo::Loader实现了以下方法,他们可以单独导入。使用use语法加载Mojo::Loader包,默认情况下并不会加载任何方法。

DATA_SECTION

my $all   = data_section 'Foo::Bar';
my $index = data_section 'Foo::Bar', 'index.html';

从指定的包的DATA段中提取SECTION,第一次对一个包调用此方法,会把所有SECTION解析出来并缓存。下次再次使用将不会重复解析,而是直接返回缓存中的内容。

# List embedded files
say for keys %{data_section 'Foo::Bar'};

file_is_binary

my $bool = file_is_binary 'Foo::Bar', 'test.png';

检查 DATA 段中的一个SECTION是否是被Base64编码的。

find_packages

my @pkgs = find_packages 'MyApp::Namespace';

在指定的命名空间中搜索已经加载的包,对子包进行递归。

find_modules

my @modules = find_modules 'MyApp::Namespace';

在指定的命名空间中搜索模块,不对子目录进行递归。

load_class

my $e = load_class 'Foo::Bar';

加载指定类并捕获异常,如果加载成功,则返回false值,如果未找到该类,返回true值,如果加载失败,则返回Mojo :: Exception对象。

注:检查类是否已经被加载使用的是$class->can('new')方法,因此尝试多次加载相同的类可能产生不同的结果。

# Handle exceptions
if (my $e = load_class 'Foo::Bar') {
  die ref $e ? "Exception: $e" : 'Not found!';
}
上一篇 下一篇

猜你喜欢

热点阅读