1Mojo::Util(3)         User Contributed Perl Documentation        Mojo::Util(3)
2
3
4

NAME

6       Mojo::Util - Portable utility functions
7

SYNOPSIS

9         use Mojo::Util qw(b64_encode url_escape url_unescape);
10
11         my $str = 'test=23';
12         my $escaped = url_escape $str;
13         say url_unescape $escaped;
14         say b64_encode $escaped, '';
15

DESCRIPTION

17       Mojo::Util provides portable utility functions for Mojo.
18

FUNCTIONS

20       Mojo::Util implements the following functions, which can be imported
21       individually.
22
23   b64_decode
24         my $bytes = b64_decode $b64;
25
26       Base64 decode bytes with MIME::Base64.
27
28   b64_encode
29         my $b64 = b64_encode $bytes;
30         my $b64 = b64_encode $bytes, "\n";
31
32       Base64 encode bytes with MIME::Base64, the line ending defaults to a
33       newline.
34
35   camelize
36         my $camelcase = camelize $snakecase;
37
38       Convert "snake_case" string to "CamelCase" and replace "-" with "::".
39
40         # "FooBar"
41         camelize 'foo_bar';
42
43         # "FooBar::Baz"
44         camelize 'foo_bar-baz';
45
46         # "FooBar::Baz"
47         camelize 'FooBar::Baz';
48
49   class_to_file
50         my $file = class_to_file 'Foo::Bar';
51
52       Convert a class name to a file.
53
54         # "foo_bar"
55         class_to_file 'Foo::Bar';
56
57         # "foobar"
58         class_to_file 'FOO::Bar';
59
60         # "foo_bar"
61         class_to_file 'FooBar';
62
63         # "foobar"
64         class_to_file 'FOOBar';
65
66   class_to_path
67         my $path = class_to_path 'Foo::Bar';
68
69       Convert class name to path, as used by %INC.
70
71         # "Foo/Bar.pm"
72         class_to_path 'Foo::Bar';
73
74         # "FooBar.pm"
75         class_to_path 'FooBar';
76
77   decamelize
78         my $snakecase = decamelize $camelcase;
79
80       Convert "CamelCase" string to "snake_case" and replace "::" with "-".
81
82         # "foo_bar"
83         decamelize 'FooBar';
84
85         # "foo_bar-baz"
86         decamelize 'FooBar::Baz';
87
88         # "foo_bar-baz"
89         decamelize 'foo_bar-baz';
90
91   decode
92         my $chars = decode 'UTF-8', $bytes;
93
94       Decode bytes to characters with Encode, or return "undef" if decoding
95       failed.
96
97   deprecated
98         deprecated 'foo is DEPRECATED in favor of bar';
99
100       Warn about deprecated feature from perspective of caller. You can also
101       set the "MOJO_FATAL_DEPRECATIONS" environment variable to make them die
102       instead with Carp.
103
104   dumper
105         my $perl = dumper {some => 'data'};
106
107       Dump a Perl data structure with Data::Dumper.
108
109   encode
110         my $bytes = encode 'UTF-8', $chars;
111
112       Encode characters to bytes with Encode.
113
114   extract_usage
115         my $usage = extract_usage;
116         my $usage = extract_usage '/home/sri/foo.pod';
117
118       Extract usage message from the SYNOPSIS section of a file containing
119       POD documentation, defaults to using the file this function was called
120       from.
121
122         # "Usage: APPLICATION test [OPTIONS]\n"
123         extract_usage;
124
125         =head1 SYNOPSIS
126
127           Usage: APPLICATION test [OPTIONS]
128
129         =cut
130
131   getopt
132         getopt
133           'H|headers=s' => \my @headers,
134           't|timeout=i' => \my $timeout,
135           'v|verbose'   => \my $verbose;
136         getopt $array,
137           'H|headers=s' => \my @headers,
138           't|timeout=i' => \my $timeout,
139           'v|verbose'   => \my $verbose;
140         getopt $array, ['pass_through'],
141           'H|headers=s' => \my @headers,
142           't|timeout=i' => \my $timeout,
143           'v|verbose'   => \my $verbose;
144
145       Extract options from an array reference with Getopt::Long, but without
146       changing its global configuration, defaults to using @ARGV. The
147       configuration options "no_auto_abbrev" and "no_ignore_case" are enabled
148       by default.
149
150         # Extract "charset" option
151         getopt ['--charset', 'UTF-8'], 'charset=s' => \my $charset;
152         say $charset;
153
154   gunzip
155         my $uncompressed = gunzip $compressed;
156
157       Uncompress bytes with IO::Compress::Gunzip.
158
159   gzip
160         my $compressed = gzip $uncompressed;
161
162       Compress bytes with IO::Compress::Gzip.
163
164   hmac_sha1_sum
165         my $checksum = hmac_sha1_sum $bytes, 'passw0rd';
166
167       Generate HMAC-SHA1 checksum for bytes with Digest::SHA.
168
169         # "11cedfd5ec11adc0ec234466d8a0f2a83736aa68"
170         hmac_sha1_sum 'foo', 'passw0rd';
171
172   html_attr_unescape
173         my $str = html_attr_unescape $escaped;
174
175       Same as "html_unescape", but handles special rules from the HTML Living
176       Standard <https://html.spec.whatwg.org> for HTML attributes.
177
178         # "foo=bar&ltest=baz"
179         html_attr_unescape 'foo=bar&ltest=baz';
180
181         # "foo=bar<est=baz"
182         html_attr_unescape 'foo=bar&lt;est=baz';
183
184   html_unescape
185         my $str = html_unescape $escaped;
186
187       Unescape all HTML entities in string.
188
189         # "<div>"
190         html_unescape '&lt;div&gt;';
191
192   humanize_bytes
193         my $str = humanize_bytes 1234;
194
195       Turn number of bytes into a simplified human readable format.
196
197         # "1B"
198         humanize_bytes 1;
199
200         # "7.5GiB"
201         humanize_bytes 8007188480;
202
203         # "13GiB"
204         humanize_bytes 13443399680;
205
206         # "-685MiB"
207         humanize_bytes -717946880;
208
209   md5_bytes
210         my $checksum = md5_bytes $bytes;
211
212       Generate binary MD5 checksum for bytes with Digest::MD5.
213
214   md5_sum
215         my $checksum = md5_sum $bytes;
216
217       Generate MD5 checksum for bytes with Digest::MD5.
218
219         # "acbd18db4cc2f85cedef654fccc4a4d8"
220         md5_sum 'foo';
221
222   monkey_patch
223         monkey_patch $package, foo => sub {...};
224         monkey_patch $package, foo => sub {...}, bar => sub {...};
225
226       Monkey patch functions into package.
227
228         monkey_patch 'MyApp',
229           one   => sub { say 'One!' },
230           two   => sub { say 'Two!' },
231           three => sub { say 'Three!' };
232
233   punycode_decode
234         my $str = punycode_decode $punycode;
235
236       Punycode decode string as described in RFC 3492
237       <https://tools.ietf.org/html/rfc3492>.
238
239         # "bücher"
240         punycode_decode 'bcher-kva';
241
242   network_contains
243         my $bool = network_contains $network, $address;
244
245       Check that a given address is contained within a network in CIDR form.
246       If the network is a single address, the addresses must be equivalent.
247
248         # True
249         network_contains('10.0.0.0/8', '10.10.10.10');
250         network_contains('10.10.10.10', '10.10.10.10');
251         network_contains('fc00::/7', 'fc::c0:ff:ee');
252
253         # False
254         network_contains('10.0.0.0/29', '10.10.10.10');
255         network_contains('10.10.10.12', '10.10.10.10');
256         network_contains('fc00::/7', '::1');
257
258   punycode_encode
259         my $punycode = punycode_encode $str;
260
261       Punycode encode string as described in RFC 3492
262       <https://tools.ietf.org/html/rfc3492>.
263
264         # "bcher-kva"
265         punycode_encode 'bücher';
266
267   quote
268         my $quoted = quote $str;
269
270       Quote string.
271
272   scope_guard
273         my $guard = scope_guard sub {...};
274
275       Create anonymous scope guard object that will execute the passed
276       callback when the object is destroyed.
277
278         # Execute closure at end of scope
279         {
280           my $guard = scope_guard sub { say "Mojo!" };
281           say "Hello";
282         }
283
284   secure_compare
285         my $bool = secure_compare $str1, $str2;
286
287       Constant time comparison algorithm to prevent timing attacks. The
288       secret string should be the second argument, to avoid leaking
289       information about the length of the string.
290
291   sha1_bytes
292         my $checksum = sha1_bytes $bytes;
293
294       Generate binary SHA1 checksum for bytes with Digest::SHA.
295
296   sha1_sum
297         my $checksum = sha1_sum $bytes;
298
299       Generate SHA1 checksum for bytes with Digest::SHA.
300
301         # "0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33"
302         sha1_sum 'foo';
303
304   slugify
305         my $slug = slugify $string;
306         my $slug = slugify $string, $bool;
307
308       Returns a URL slug generated from the input string. Non-word characters
309       are removed, the string is trimmed and lowercased, and whitespace
310       characters are replaced by a dash. By default, non-ASCII characters are
311       normalized to ASCII word characters or removed, but if a true value is
312       passed as the second parameter, all word characters will be allowed in
313       the result according to unicode semantics.
314
315         # "joel-is-a-slug"
316         slugify 'Joel is a slug';
317
318         # "this-is-my-resume"
319         slugify 'This is: my - résumé! ☃ ';
320
321         # "this-is-my-résumé"
322         slugify 'This is: my - résumé! ☃ ', 1;
323
324   split_cookie_header
325         my $tree = split_cookie_header 'a=b; expires=Thu, 07 Aug 2008 07:07:59 GMT';
326
327       Same as "split_header", but handles "expires" values from RFC 6265
328       <https://tools.ietf.org/html/rfc6265>.
329
330   split_header
331          my $tree = split_header 'foo="bar baz"; test=123, yada';
332
333       Split HTTP header value into key/value pairs, each comma separated part
334       gets its own array reference, and keys without a value get "undef"
335       assigned.
336
337         # "one"
338         split_header('one; two="three four", five=six')->[0][0];
339
340         # "two"
341         split_header('one; two="three four", five=six')->[0][2];
342
343         # "three four"
344         split_header('one; two="three four", five=six')->[0][3];
345
346         # "five"
347         split_header('one; two="three four", five=six')->[1][0];
348
349         # "six"
350         split_header('one; two="three four", five=six')->[1][1];
351
352   steady_time
353         my $time = steady_time;
354
355       High resolution time elapsed from an arbitrary fixed point in the past,
356       resilient to time jumps if a monotonic clock is available through
357       Time::HiRes.
358
359   tablify
360         my $table = tablify [['foo', 'bar'], ['baz', 'yada']];
361
362       Row-oriented generator for text tables.
363
364         # "foo   bar\nyada  yada\nbaz   yada\n"
365         tablify [['foo', 'bar'], ['yada', 'yada'], ['baz', 'yada']];
366
367   term_escape
368         my $escaped = term_escape $str;
369
370       Escape all POSIX control characters except for "\n".
371
372         # "foo\\x09bar\\x0d\n"
373         term_escape "foo\tbar\r\n";
374
375   trim
376         my $trimmed = trim $str;
377
378       Trim whitespace characters from both ends of string.
379
380         # "foo bar"
381         trim '  foo bar  ';
382
383   unindent
384         my $unindented = unindent $str;
385
386       Unindent multi-line string.
387
388         # "foo\nbar\nbaz\n"
389         unindent "  foo\n  bar\n  baz\n";
390
391   unquote
392         my $str = unquote $quoted;
393
394       Unquote string.
395
396   url_escape
397         my $escaped = url_escape $str;
398         my $escaped = url_escape $str, '^A-Za-z0-9\-._~';
399
400       Percent encode unsafe characters in string as described in RFC 3986
401       <https://tools.ietf.org/html/rfc3986>, the pattern used defaults to
402       "^A-Za-z0-9\-._~".
403
404         # "foo%3Bbar"
405         url_escape 'foo;bar';
406
407   url_unescape
408         my $str = url_unescape $escaped;
409
410       Decode percent encoded characters in string as described in RFC 3986
411       <https://tools.ietf.org/html/rfc3986>.
412
413         # "foo;bar"
414         url_unescape 'foo%3Bbar';
415
416   xml_escape
417         my $escaped = xml_escape $str;
418
419       Escape unsafe characters "&", "<", ">", """ and "'" in string, but do
420       not escape Mojo::ByteStream objects.
421
422         # "&lt;div&gt;"
423         xml_escape '<div>';
424
425         # "<div>"
426         use Mojo::ByteStream qw(b);
427         xml_escape b('<div>');
428
429   xor_encode
430         my $encoded = xor_encode $str, $key;
431
432       XOR encode string with variable length key.
433

SEE ALSO

435       Mojolicious, Mojolicious::Guides, <https://mojolicious.org>.
436
437
438
439perl v5.34.0                      2022-01-21                     Mojo::Util(3)
Impressum