Do you uuencode? Perl's pack does!

In my previous post, I presented what I thought was a cute way to include encoded binary data in the __DATA__ section of a Perl file.

On /r/perl, kazuma_k pointed out that I could have just used 'u' with pack/unpack.

Hmmm … I know what 'U' does. What does 'u' do?

perldoc just says:

u  A uuencoded string.

I used to use uuencoding a lot … I think the first time I saw it was more than 25 years ago. The last time I used it was when I stopped using Eudora as my email client on Windows 3. In fact, I hadn’t heard the term in so long that I had forgotten all about it until this helpful post.

If you don’t already know what it is, perldoc is not going to tell you, apparently.Well, let’s see what we can do with it.

We are starting again with the 249 byte QR code image for ν42’s URL, and a Perl source file to which we want to append its encoded data.

With unpack 'u', the code to decode the image is simply:

my $png = unpack 'u', do { local $/; scalar <DATA> };

With pack 'u', we don’t need any external utilities:

C:\...> perl -e "binmode STDOUT; print pack 'u', do {
 binmode STDIN; local $/; scalar <STDIN> }" < qrcode.png >> ubundler.pl

There, binmode STDOUT is necessary because I use Unix style line-endings in my source code files on Windows. If I don’t specify it, perl will put a bunch of carriage returns in my files which will show up as ^Ms in Vim.

binmode STDIN is needed on Windows because I do not want perl to do CRLF translation on the PNG file.

With the encoded image data in place, this script will extract and save it on your computer:

binmode STDOUT;
print unpack 'u', do { local $/; scalar <DATA> };

__DATA__
MB5!.1PT*&@H````-24A$4@```-@```#8`0,```"S[K^N````!E!,5$4```#_
M__^EV9_=````KDE$051X7MW500J`,!0#T=S_TA4S!+OQ`A.D_.;]C2"8\Q^'
MA;P3NVLLQGM27XW'[email protected]?%ZU&*S3:]8?&8X3Y:BQVA7X7B:4>#FZA=UB[
MH""GPS@0AIT6V[76>7>'!=]:&3$8Q9""N\4RRKJ)PPYM2GW@(['L/>%D6Q(C
M3/MPV7982,MDW?'8]PTCNVDLU^]_04S6,*(JJZ;,D&BLS<HT=`XCIP\KK$KL
8-PI[`%<G.WR[J/SW`````$E%3D2N0F""

Of course, one disadvantage of uuencode is the fact that you need to make sure all the & and < characters are properly escaped if you are going to included the encoded chunk on a web page ;-)