Mojo::Util(3)
π NAME π
Mojo::Util β Portable utility functions π
β¨
(aka the Mojo::Util(3) page from the User Contributed Perl Documentation β hiii, welcome, come sit with us π«Ά)
πΈ SYNOPSIS πΈ
use Mojo::Util qw(b64_encode url_escape url_unescape);
my $str = 'test=23';
my $escaped = url_escape $str;
say url_unescape $escaped;
say b64_encode $escaped, '';
π¦ DESCRIPTION π¦
okay so Mojo::Util provides portable utility functions for Mojo. That's literally the whole vibe. It's giving Swiss Army knife but make it Perl. π
β¨ FUNCTIONS β¨
Mojo::Util implements the following functions, and β slay β you can import each one individually. No need to drag the whole friend group along if you only need one. π
π b64_decode
my $bytes = b64_decode $b64;
Base64 decode bytes with MIME::Base64. Turning your cute little b64 blob back into raw bytes, iconic. π₯
π b64_encode
my $b64 = b64_encode $bytes;
my $b64 = b64_encode $bytes, "\n";
Base64 encode bytes with MIME::Base64. The line ending defaults to a newline, so if you don't pass one it's already handled for you. π
π camelize
my $camelcase = camelize $snakecase;
Convert a "snake_case" string to "CamelCase" and replace "-" with "::". Glow-up transformation, honestly.
# "FooBar"
camelize 'foo_bar';
# "FooBar::Baz"
camelize 'foo_bar-baz';
# "FooBar::Baz"
camelize 'FooBar::Baz';
π class_to_file
my $file = class_to_file 'Foo::Bar';
Convert a class name to a file. Lowkey essential.
# "foo_bar"
class_to_file 'Foo::Bar';
# "foobar"
class_to_file 'FOO::Bar';
# "foo_bar"
class_to_file 'FooBar';
# "foobar"
class_to_file 'FOOBar';
π class_to_path
my $path = class_to_path 'Foo::Bar';
Convert class name to path, as used by %INC. Yes, that %INC.
# "Foo/Bar.pm"
class_to_path 'Foo::Bar';
# "FooBar.pm"
class_to_path 'FooBar';
π decamelize
my $snakecase = decamelize $camelcase;
Convert a "CamelCase" string to "snake_case" and replace "::" with "-". The reverse makeover. π
# "foo_bar"
decamelize 'FooBar';
# "foo_bar-baz"
decamelize 'FooBar::Baz';
# "foo_bar-baz"
decamelize 'foo_bar-baz';
π decode
my $chars = decode 'UTF-8', $bytes;
Decode bytes to characters with Encode β or return "undef" if decoding failed. So like, check for undef, bestie, fr fr. π
π decrypt_cookie
my $value = decrypt_cookie $encrypted, 'passw0rd', 'salt';
Decrypt a cookie value encrypted with "encrypt_cookie". Returns the decrypted value or "undef". Spy-movie energy. π΅οΈ
π deprecated
deprecated 'foo is DEPRECATED in favor of bar';
Warn about a deprecated feature from the perspective of the caller. And get this β you can also set the "MOJO_FATAL_DEPRECATIONS" environment variable to make them die instead with Carp. Dramatic? yes. Useful? also yes. π
π dumper
my $perl = dumper {some => 'data'};
Dump a Perl data structure with Data::Dumper. Look at your data, isn't it cute. π
π encode
my $bytes = encode 'UTF-8', $chars;
Encode characters to bytes with Encode. The other direction of the decode situation.
π encrypt_cookie
my $encrypted = encrypt_cookie $value, 'passw0rd', 'salt';
Encrypt cookie value. That's the whole description, it's giving mysterious. π
π extract_usage
my $usage = extract_usage;
my $usage = extract_usage '/home/sri/foo.pod';
Extract the usage message from the SYNOPSIS section of a file containing POD documentation. It defaults to using the file this function was called from β sneaky but iconic.
# "Usage: APPLICATION test [OPTIONS]\n"
extract_usage;
=head1 SYNOPSIS
Usage: APPLICATION test [OPTIONS]
=cut
π generate_secret
my $secret = generate_secret;
Generate a random secret with a cryptographically secure random number generator. Not your cousin's birthday, a real secret. π₯
π getopt
getopt
'H|headers=s' => \my @headers,
't|timeout=i' => \my $timeout,
'v|verbose' => \my $verbose;
getopt $array,
'H|headers=s' => \my @headers,
't|timeout=i' => \my $timeout,
'v|verbose' => \my $verbose;
getopt $array, ['pass_through'],
'H|headers=s' => \my @headers,
't|timeout=i' => \my $timeout,
'v|verbose' => \my $verbose;
Extract options from an array reference with Getopt::Long, but without changing its global configuration β respectful king behavior. It defaults to using @ARGV. The configuration options "no_auto_abbrev" and "no_ignore_case" are enabled by default. π
# Extract "charset" option
getopt ['--charset', 'UTF-8'], 'charset=s' => \my $charset;
say $charset;
π gunzip
my $uncompressed = gunzip $compressed;
Uncompress bytes with IO::Compress::Gunzip. Un-squish. π«§
π gzip
my $compressed = gzip $uncompressed;
Compress bytes with IO::Compress::Gzip. Squish. ποΈ
π header_params
my ($params, $remainder) = header_params 'one=foo; two="bar", three=baz';
Extract HTTP header field parameters until the first comma according to RFC 5987 β link's right here: http://tools.ietf.org/html/rfc5987. Two return values, she's thorough. β¨
π hmac_sha1_sum
my $checksum = hmac_sha1_sum $bytes, 'passw0rd';
Generate an HMAC-SHA1 checksum for bytes with Digest::SHA.
# "11cedfd5ec11adc0ec234466d8a0f2a83736aa68"
hmac_sha1_sum 'foo', 'passw0rd';
π html_attr_unescape
my $str = html_attr_unescape $escaped;
Same as "html_unescape", but it handles the special rules from the HTML Living Standard (https://html.spec.whatwg.org) for HTML attributes. Fancy rules, fancy function.
# "foo=bar<est=baz"
html_attr_unescape 'foo=bar<est=baz';
# "foo=bar<est=baz"
html_attr_unescape 'foo=bar<est=baz';
π html_unescape
my $str = html_unescape $escaped;
Unescape all HTML entities in the string. Every single one, bestie.
# "<div>"
html_unescape '<div>';
π humanize_bytes
my $str = humanize_bytes 1234;
Turn a number of bytes into a simplified human readable format. So your brain doesn't have to count zeros. π§ β¨
# "1B"
humanize_bytes 1;
# "7.5GiB"
humanize_bytes 8007188480;
# "13GiB"
humanize_bytes 13443399680;
# "-685MiB"
humanize_bytes -717946880;
π md5_bytes
my $checksum = md5_bytes $bytes;
Generate a binary MD5 checksum for bytes with Digest::MD5.
π md5_sum
my $checksum = md5_sum $bytes;
Generate an MD5 checksum for bytes with Digest::MD5. The hex-y one.
# "acbd18db4cc2f85cedef654fccc4a4d8"
md5_sum 'foo';
π monkey_patch
monkey_patch $package, foo => sub {...};
monkey_patch $package, foo => sub {...}, bar => sub {...};
Monkey patch functions into a package. Chaos, but organized chaos. π
monkey_patch 'MyApp',
one => sub { say 'One!' },
two => sub { say 'Two!' },
three => sub { say 'Three!' };
π network_contains
my $bool = network_contains $network, $address;
Check that a given address is contained within a network in CIDR form. If the network is a single address, the addresses must be equivalent β no fuzzy matching, it's strict. π
# True
network_contains('10.0.0.0/8', '10.10.10.10');
network_contains('10.10.10.10', '10.10.10.10');
network_contains('fc00::/7', 'fc::c0:ff:ee');
# False
network_contains('10.0.0.0/29', '10.10.10.10');
network_contains('10.10.10.12', '10.10.10.10');
network_contains('fc00::/7', '::1');
π punycode_decode
my $str = punycode_decode $punycode;
Punycode decode a string as described in RFC 3492 β that's https://tools.ietf.org/html/rfc3492 for the record.
# "bΓΌcher"
punycode_decode 'bcher-kva';
π punycode_encode
my $punycode = punycode_encode $str;
Punycode encode a string as described in RFC 3492 β https://tools.ietf.org/html/rfc3492. Yep, same RFC, opposite direction.
# "bcher-kva"
punycode_encode 'bΓΌcher';
π quote
my $quoted = quote $str;
Quote string. Short, sweet, to the point. π
π random_bytes
my $random = random_bytes($bytes);
Generate $bytes worth of high entropy randomness. Maximum chaos, cryptographically speaking. π²
π scope_guard
my $guard = scope_guard sub {...};
Create an anonymous scope guard object that will execute the passed callback when the object is destroyed. Set it and forget it, then it fires at the end. π€«
# Execute closure at end of scope
{
my $guard = scope_guard sub { say "Mojo!" };
say "Hello";
}
π secure_compare
my $bool = secure_compare $str1, $str2;
A constant time comparison algorithm to prevent timing attacks. Important detail: the secret string should be the second argument, to avoid leaking information about the length of the string. Don't mix that up, bestie, fr fr. π
π sha1_bytes
my $checksum = sha1_bytes $bytes;
Generate a binary SHA1 checksum for bytes with Digest::SHA.
π sha1_sum
my $checksum = sha1_sum $bytes;
Generate a SHA1 checksum for bytes with Digest::SHA. The hex-y sibling of sha1_bytes.
# "0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33"
sha1_sum 'foo';
π slugify
my $slug = slugify $string;
my $slug = slugify $string, $bool;
Returns a URL slug generated from the input string. So here's the tea: non-word characters are removed, the string is trimmed and lowercased, and whitespace characters are replaced by a dash. By default, non-ASCII characters are normalized to ASCII word characters or removed β but if you pass a true value as the second parameter, all word characters will be allowed in the result according to unicode semantics. She contains multitudes. π
# "joel-is-a-slug"
slugify 'Joel is a slug';
# "this-is-my-resume"
slugify 'This is: my - rΓ©sumΓ©! β ';
# "this-is-my-rΓ©sumΓ©"
slugify 'This is: my - rΓ©sumΓ©! β ', 1;
π split_cookie_header
my $tree = split_cookie_header 'a=b; expires=Thu, 07 Aug 2008 07:07:59 GMT';
Same as "split_header", but it handles "expires" values from RFC 6265 β https://tools.ietf.org/html/rfc6265. Cookies stay winning. πͺ
π split_header
my $tree = split_header 'foo="bar baz"; test=123, yada';
Split an HTTP header value into key/value pairs. Each comma separated part gets its own array reference, and keys without a value get "undef" assigned. Yes, undef, don't @ me.
# "one"
split_header('one; two="three four", five=six')->[0][0];
# "two"
split_header('one; two="three four", five=six')->[0][2];
# "three four"
split_header('one; two="three four", five=six')->[0][3];
# "five"
split_header('one; two="three four", five=six')->[1][0];
# "six"
split_header('one; two="three four", five=six')->[1][1];
π steady_time
my $time = steady_time;
High resolution time elapsed from an arbitrary fixed point in the past, resilient to time jumps if a monotonic clock is available through Time::HiRes. So like, time that refuses to be gaslit by clock changes. β°π
π tablify
my $table = tablify [['foo', 'bar'], ['baz', 'yada']];
Row-oriented generator for text tables. Little ASCII picnic table for your data. π§Ί
# "foo bar\nyada yada\nbaz yada\n"
tablify [['foo', 'bar'], ['yada', 'yada'], ['baz', 'yada']];
π term_escape
my $escaped = term_escape $str;
Escape all POSIX control characters except for "\n". Note the exception, bestie β the newline stays, everything else gets esc-aped. π
# "foo\\x09bar\\x0d\n"
term_escape "foo\tbar\r\n";
π trim
my $trimmed = trim $str;
Trim whitespace characters from both ends of the string. Not one end. Both. Symmetry queen. βοΈ
# "foo bar"
trim ' foo bar ';
π unindent
my $unindented = unindent $str;
Unindent a multi-line string. Dedenting but make it a function.
# "foo\nbar\nbaz\n"
unindent " foo\n bar\n baz\n";
π unquote
my $str = unquote $quoted;
Unquote string. The quote function's other half. π«Ά
π url_escape
my $escaped = url_escape $str;
my $escaped = url_escape $str, '^A-Za-z0-9\-._~';
Percent encode unsafe characters in the string as described in RFC 3986 β https://tools.ietf.org/html/rfc3986. The pattern used defaults to "^A-Za-z0-9\-._~", so that's what's getting let through unless you say otherwise.
# "foo%3Bbar"
url_escape 'foo;bar';
π url_unescape
my $str = url_unescape $escaped;
Decode percent encoded characters in the string as described in RFC 3986 β https://tools.ietf.org/html/rfc3986. The reverse slay of url_escape. πΈ
# "foo;bar"
url_unescape 'foo%3Bbar';
Like, <cyan>boom</cyan> β the %3B was hiding a semicolon the whole time and now it's out here living its truth. π¦ That's the entire arc of url_unescape, bestie, no notes.
β¨ xml_escape β¨
my $escaped = xml_escape $str;
Okay so this one is your little XML bodyguard π«Ά β it escapes the unsafe characters &, <, >, " and ' in a string so they can't wreak havoc. Very protective, very demure. But <hotpink>important plot twist</hotpink>: it does not escape Mojo::ByteStream objects. Those are already built different and get left exactly as they are, periodt.
# "<div>"
xml_escape '<div>';
See how the angle brackets got all shy and turned into < / >? Iconic behaviour honestly. π
# "<div>"
use Mojo::ByteStream qw(b);
xml_escape b('<div>');
And here β a Mojo::ByteStream (that's the b(...) wrapper, iykyk) rolls up and comes back out completely untouched as <div>. Not a single character changed. Main character energy, the escaping simply does not apply to it. π
π xor_encode π
my $encoded = xor_encode $str, $key;
XOR encodes a string using a key of variable length. That's the whole thing β your string goes in, gets XOR'd against $key (and the key can literally be any length, no rules, no gatekeeping β¨), and the encoded result comes back out. Very "we do a little cryptography" of it. π₯
π SEE ALSO π
MojoliciousMojolicious::Guides- <https://mojolicious.org>
Go read those, bestie, they're the moment. π
fr fr though β that's genuinely the end of the page, nothing got skipped, every flag and example is present and accounted for π
okay and that's a wrap on this one πΈ this page is from perl v5.42.0, dated 2026-07-15, so if your install says something else, you're on a different timeline, bestie β check your version and stay hydrated πβ¨
π¦ where this page comes from
- opensuse-leap 16.0: perl-Mojolicious 9.480.0-bp160.2.1 Β· Artistic-2.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms