1Mojo::Loader(3) User Contributed Perl Documentation Mojo::Loader(3)
2
3
4
6 Mojo::Loader - Load all kinds of things
7
9 use Mojo::Loader qw(data_section find_modules load_class);
10
11 # Find modules in a namespace
12 for my $module (find_modules 'Some::Namespace') {
13
14 # Load them safely
15 my $e = load_class $module;
16 warn qq{Loading "$module" failed: $e} and next if ref $e;
17
18 # And extract files from the DATA section
19 say data_section($module, 'some_file.txt');
20 }
21
23 Mojo::Loader is a class loader and plugin framework. Aside from finding
24 modules and loading classes, it allows multiple files to be stored in
25 the "DATA" section of a class, which can then be accessed individually.
26
27 package Foo;
28
29 1;
30 __DATA__
31
32 @@ test.txt
33 This is the first file.
34
35 @@ test2.html (base64)
36 VGhpcyBpcyB0aGUgc2Vjb25kIGZpbGUu
37
38 @@ test
39 This is the
40 third file.
41
42 Each file has a header starting with "@@", followed by the file name
43 and optional instructions for decoding its content. Currently only the
44 Base64 encoding is supported, which can be quite convenient for the
45 storage of binary data.
46
48 Mojo::Loader implements the following functions, which can be imported
49 individually.
50
51 data_section
52 my $all = data_section 'Foo::Bar';
53 my $index = data_section 'Foo::Bar', 'index.html';
54
55 Extract embedded file from the "DATA" section of a class, all files
56 will be cached once they have been accessed for the first time.
57
58 # List embedded files
59 say for keys %{data_section 'Foo::Bar'};
60
61 file_is_binary
62 my $bool = file_is_binary 'Foo::Bar', 'test.png';
63
64 Check if embedded file from the "DATA" section of a class was Base64
65 encoded.
66
67 find_packages
68 my @pkgs = find_packages 'MyApp::Namespace';
69
70 Search for packages in a namespace non-recursively.
71
72 find_modules
73 my @modules = find_modules 'MyApp::Namespace';
74 my @modules = find_modules 'MyApp::Namespace', {recursive => 1};
75
76 Search for modules in a namespace.
77
78 These options are currently available:
79
80 recursive
81 recursive => 1
82
83 Search namespace recursively.
84
85 load_class
86 my $e = load_class 'Foo::Bar';
87
88 Load a class and catch exceptions, returns a false value if loading was
89 successful, a true value if the class was not found, or a
90 Mojo::Exception object if loading failed. Note that classes are checked
91 for a "new" method to see if they are already loaded, so trying to load
92 the same class multiple times may yield different results.
93
94 # Handle exceptions
95 if (my $e = load_class 'Foo::Bar') {
96 die ref $e ? "Exception: $e" : 'Not found!';
97 }
98
99 load_classes
100 my @classes = load_classes 'Foo::Bar';
101
102 Load all classes in a namespace recursively.
103
105 Mojolicious, Mojolicious::Guides, <https://mojolicious.org>.
106
107
108
109perl v5.38.0 2023-09-11 Mojo::Loader(3)