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   header_params
165         my ($params, $remainder) = header_params 'one=foo; two="bar", three=baz';
166
167       Extract HTTP header field parameters until the first comma according to
168       RFC 5987 <http://tools.ietf.org/html/rfc5987>.  Note that this function
169       is EXPERIMENTAL and might change without warning!
170
171   hmac_sha1_sum
172         my $checksum = hmac_sha1_sum $bytes, 'passw0rd';
173
174       Generate HMAC-SHA1 checksum for bytes with Digest::SHA.
175
176         # "11cedfd5ec11adc0ec234466d8a0f2a83736aa68"
177         hmac_sha1_sum 'foo', 'passw0rd';
178
179   html_attr_unescape
180         my $str = html_attr_unescape $escaped;
181
182       Same as "html_unescape", but handles special rules from the HTML Living
183       Standard <https://html.spec.whatwg.org> for HTML attributes.
184
185         # "foo=bar&ltest=baz"
186         html_attr_unescape 'foo=bar&ltest=baz';
187
188         # "foo=bar<est=baz"
189         html_attr_unescape 'foo=bar&lt;est=baz';
190
191   html_unescape
192         my $str = html_unescape $escaped;
193
194       Unescape all HTML entities in string.
195
196         # "<div>"
197         html_unescape '&lt;div&gt;';
198
199   humanize_bytes
200         my $str = humanize_bytes 1234;
201
202       Turn number of bytes into a simplified human readable format.
203
204         # "1B"
205         humanize_bytes 1;
206
207         # "7.5GiB"
208         humanize_bytes 8007188480;
209
210         # "13GiB"
211         humanize_bytes 13443399680;
212
213         # "-685MiB"
214         humanize_bytes -717946880;
215
216   md5_bytes
217         my $checksum = md5_bytes $bytes;
218
219       Generate binary MD5 checksum for bytes with Digest::MD5.
220
221   md5_sum
222         my $checksum = md5_sum $bytes;
223
224       Generate MD5 checksum for bytes with Digest::MD5.
225
226         # "acbd18db4cc2f85cedef654fccc4a4d8"
227         md5_sum 'foo';
228
229   monkey_patch
230         monkey_patch $package, foo => sub {...};
231         monkey_patch $package, foo => sub {...}, bar => sub {...};
232
233       Monkey patch functions into package.
234
235         monkey_patch 'MyApp',
236           one   => sub { say 'One!' },
237           two   => sub { say 'Two!' },
238           three => sub { say 'Three!' };
239
240   punycode_decode
241         my $str = punycode_decode $punycode;
242
243       Punycode decode string as described in RFC 3492
244       <https://tools.ietf.org/html/rfc3492>.
245
246         # "bücher"
247         punycode_decode 'bcher-kva';
248
249   network_contains
250         my $bool = network_contains $network, $address;
251
252       Check that a given address is contained within a network in CIDR form.
253       If the network is a single address, the addresses must be equivalent.
254
255         # True
256         network_contains('10.0.0.0/8', '10.10.10.10');
257         network_contains('10.10.10.10', '10.10.10.10');
258         network_contains('fc00::/7', 'fc::c0:ff:ee');
259
260         # False
261         network_contains('10.0.0.0/29', '10.10.10.10');
262         network_contains('10.10.10.12', '10.10.10.10');
263         network_contains('fc00::/7', '::1');
264
265   punycode_encode
266         my $punycode = punycode_encode $str;
267
268       Punycode encode string as described in RFC 3492
269       <https://tools.ietf.org/html/rfc3492>.
270
271         # "bcher-kva"
272         punycode_encode 'bücher';
273
274   quote
275         my $quoted = quote $str;
276
277       Quote string.
278
279   scope_guard
280         my $guard = scope_guard sub {...};
281
282       Create anonymous scope guard object that will execute the passed
283       callback when the object is destroyed.
284
285         # Execute closure at end of scope
286         {
287           my $guard = scope_guard sub { say "Mojo!" };
288           say "Hello";
289         }
290
291   secure_compare
292         my $bool = secure_compare $str1, $str2;
293
294       Constant time comparison algorithm to prevent timing attacks. The
295       secret string should be the second argument, to avoid leaking
296       information about the length of the string.
297
298   sha1_bytes
299         my $checksum = sha1_bytes $bytes;
300
301       Generate binary SHA1 checksum for bytes with Digest::SHA.
302
303   sha1_sum
304         my $checksum = sha1_sum $bytes;
305
306       Generate SHA1 checksum for bytes with Digest::SHA.
307
308         # "0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33"
309         sha1_sum 'foo';
310
311   slugify
312         my $slug = slugify $string;
313         my $slug = slugify $string, $bool;
314
315       Returns a URL slug generated from the input string. Non-word characters
316       are removed, the string is trimmed and lowercased, and whitespace
317       characters are replaced by a dash. By default, non-ASCII characters are
318       normalized to ASCII word characters or removed, but if a true value is
319       passed as the second parameter, all word characters will be allowed in
320       the result according to unicode semantics.
321
322         # "joel-is-a-slug"
323         slugify 'Joel is a slug';
324
325         # "this-is-my-resume"
326         slugify 'This is: my - résumé! ☃ ';
327
328         # "this-is-my-résumé"
329         slugify 'This is: my - résumé! ☃ ', 1;
330
331   split_cookie_header
332         my $tree = split_cookie_header 'a=b; expires=Thu, 07 Aug 2008 07:07:59 GMT';
333
334       Same as "split_header", but handles "expires" values from RFC 6265
335       <https://tools.ietf.org/html/rfc6265>.
336
337   split_header
338          my $tree = split_header 'foo="bar baz"; test=123, yada';
339
340       Split HTTP header value into key/value pairs, each comma separated part
341       gets its own array reference, and keys without a value get "undef"
342       assigned.
343
344         # "one"
345         split_header('one; two="three four", five=six')->[0][0];
346
347         # "two"
348         split_header('one; two="three four", five=six')->[0][2];
349
350         # "three four"
351         split_header('one; two="three four", five=six')->[0][3];
352
353         # "five"
354         split_header('one; two="three four", five=six')->[1][0];
355
356         # "six"
357         split_header('one; two="three four", five=six')->[1][1];
358
359   steady_time
360         my $time = steady_time;
361
362       High resolution time elapsed from an arbitrary fixed point in the past,
363       resilient to time jumps if a monotonic clock is available through
364       Time::HiRes.
365
366   tablify
367         my $table = tablify [['foo', 'bar'], ['baz', 'yada']];
368
369       Row-oriented generator for text tables.
370
371         # "foo   bar\nyada  yada\nbaz   yada\n"
372         tablify [['foo', 'bar'], ['yada', 'yada'], ['baz', 'yada']];
373
374   term_escape
375         my $escaped = term_escape $str;
376
377       Escape all POSIX control characters except for "\n".
378
379         # "foo\\x09bar\\x0d\n"
380         term_escape "foo\tbar\r\n";
381
382   trim
383         my $trimmed = trim $str;
384
385       Trim whitespace characters from both ends of string.
386
387         # "foo bar"
388         trim '  foo bar  ';
389
390   unindent
391         my $unindented = unindent $str;
392
393       Unindent multi-line string.
394
395         # "foo\nbar\nbaz\n"
396         unindent "  foo\n  bar\n  baz\n";
397
398   unquote
399         my $str = unquote $quoted;
400
401       Unquote string.
402
403   url_escape
404         my $escaped = url_escape $str;
405         my $escaped = url_escape $str, '^A-Za-z0-9\-._~';
406
407       Percent encode unsafe characters in string as described in RFC 3986
408       <https://tools.ietf.org/html/rfc3986>, the pattern used defaults to
409       "^A-Za-z0-9\-._~".
410
411         # "foo%3Bbar"
412         url_escape 'foo;bar';
413
414   url_unescape
415         my $str = url_unescape $escaped;
416
417       Decode percent encoded characters in string as described in RFC 3986
418       <https://tools.ietf.org/html/rfc3986>.
419
420         # "foo;bar"
421         url_unescape 'foo%3Bbar';
422
423   xml_escape
424         my $escaped = xml_escape $str;
425
426       Escape unsafe characters "&", "<", ">", """ and "'" in string, but do
427       not escape Mojo::ByteStream objects.
428
429         # "&lt;div&gt;"
430         xml_escape '<div>';
431
432         # "<div>"
433         use Mojo::ByteStream qw(b);
434         xml_escape b('<div>');
435
436   xor_encode
437         my $encoded = xor_encode $str, $key;
438
439       XOR encode string with variable length key.
440

SEE ALSO

442       Mojolicious, Mojolicious::Guides, <https://mojolicious.org>.
443
444
445
446perl v5.36.0                      2023-01-20                     Mojo::Util(3)
Impressum