Base64 Encoding in Perl
Perl provides built-in support for base64 encoding/decoding through the MIME::Base64 module.
This syntax imports the MIME::Base64
module, which provides functions for base64 encoding and decoding.
Here’s the string we’ll encode/decode.
Perl supports standard base64 encoding/decoding through the encode_base64
and decode_base64
functions. The encoder takes a string as input and returns the encoded string. The decoder does the reverse.
For URL-safe base64 encoding, we first encode normally, then replace ‘+’ with ‘-’ and ‘/’ with ‘_’. For decoding, we reverse this process before using the standard decoder.
When you run this Perl script, you’ll see output similar to the following:
The string encodes to slightly different values with the standard and URL-safe base64 encoders (trailing +
vs -
) but they both decode to the original string as desired.
In Perl, error handling for decoding is typically done by checking if the decoded string is defined. If the input is not valid base64, the decode function will return undef
.