Subject: | Documentation tweak |
Date: | Fri, 26 Sep 2014 11:41:17 -0600 |
To: | bug-Digest-SHA [...] rt.cpan.org |
From: | Warren Young <warren [...] etr-usa.com> |
Hi,
I thought you might like to give this trick in the Digest::SHA docs in
place of the current while loop you have for padding Base64 strings:
$b64_digest .= '=' x (-length($b64_digest) % 4);
It not only does the same work in a single line, it avoids the loop
entirely.
The math is a little tricky. length($b64_digest) % 4 tells us how many
characters over the next lower multiple of 4 we are. By negating the
length first, we get the number of characters to the *next* multiple of
4, which tells us how many = signs to append. Perl's uncommon 'x'
operator does the rest.
I confess that I did not come up with this numeric trick myself. I
initially constructed it like this:
$b64_digest .= '=' x ((4 - (length($b64_digest) % 4)) % 4);
I thought there had to be a better way to express it, so I asked Wolfram
Alpha, and it came up with the formulation above. :)