ETOOBUSY 🚀 minimal blogging for the impatient
Base64 in Perl
TL;DR
In a previous post we looked at Base64, an encoding mechanism that allows to transform generic binary data into a restricted set of ASCII characters. What if you don’t have base64 but you have Perl instead?
Use MIME::Base64!
Encode with encode_base64
(imported automatically):
$ printf 'whatevah!' | base64
d2hhdGV2YWgh
$ printf 'whatevah!' \
| perl -MMIME::Base64 -e 'local $/; print encode_base64(<>)'
d2hhdGV2YWgh
Decode with decode_base64
(again, imported automatically):
$ printf 'd2hhdGV2YWgh' | base64 -d ; echo
whatevah!
$ printf 'd2hhdGV2YWgh' \
| perl -MMIME::Base64 -e 'local $/; print decode_base64(<>)' ; echo
whatevah!
Just like base64, MIME::Base64 will break long output encoded lines with newlines. This can be seen with a longer input:
$ perl -e 'print "whatevah!" x 10' | base64
d2hhdGV2YWghd2hhdGV2YWghd2hhdGV2YWghd2hhdGV2YWghd2hhdGV2YWghd2hhdGV2YWghd2hh
dGV2YWghd2hhdGV2YWghd2hhdGV2YWghd2hhdGV2YWgh
$ perl -e 'print "whatevah!" x 10' \
| perl -MMIME::Base64 -e 'local $/; print encode_base64(<>)'
d2hhdGV2YWghd2hhdGV2YWghd2hhdGV2YWghd2hhdGV2YWghd2hhdGV2YWghd2hhdGV2YWghd2hh
dGV2YWghd2hhdGV2YWghd2hhdGV2YWghd2hhdGV2YWgh
If you just want a single uninterrupted string, just pass a second parameter with the separator (e.g. the empty string):
$ perl -e 'print "whatevah!" x 10' | base64 -w 0 ; echo
d2hhdGV2YWghd2hhdGV2YWghd2hhdGV2YWghd2hhdGV2YWghd2hhdGV2YWghd2hhdGV2YWghd2hhdGV2YWghd2hhdGV2YWghd2hhdGV2YWghd2hhdGV2YWgh
$ perl -e 'print "whatevah!" x 10' \
| perl -MMIME::Base64 -e 'local $/; print encode_base64(<>, "")' ; echo
d2hhdGV2YWghd2hhdGV2YWghd2hhdGV2YWghd2hhdGV2YWghd2hhdGV2YWghd2hhdGV2YWghd2hhdGV2YWghd2hhdGV2YWghd2hhdGV2YWghd2hhdGV2YWgh
This is pretty much it!