tags:

views:

279

answers:

3

I am trying to compare an encode_base64('test') to the string variable containing the base64 string of 'test'. The problem is it never validates!

use MIMI::Base64 qw(encode_base64);

if (encode_base64("test") eq "dGVzdA==")
{
    print "true";
}

Am I forgetting anything?

+6  A: 

Here's a link to a Perlmonks page which says "Beware of the newline at the end of the encode_base64() encoded strings".

So the simple 'eq' may fail.

To suppress the newline, say encode_base64("test", "") instead.

pavium
true! thanks! should have paid more attention to my print
Bob
+5  A: 

When you do a string comparison and it fails unexpectedly, print the strings to see what is actually in them. I put brackets around the value to see any extra whitespace:

use MIME::Base64;

$b64 = encode_base64("test");

print "b64 is [$b64]\n";

if ($b64 eq "dGVzdA==") {
   print "true";
}

This is a basic debugging technique using the best debugger ever invented. Get used to using it a lot. :)

Also, sometimes you need to read the documentation for things a couple time to catch the important parts. In this case, MIME::Base64 tells you that encode_base64 takes two arguments. The second argument is the line ending and defaults to a newline. If you don't want a newline on the end of the string you need to give it another line ending, such as the empty string.

brian d foy
A: 

Here's an interesting tip: use Perl's wonderful and well-loved testing modules for debugging. Not only will that give you a head start on testing, but sometimes they'll make your debugging output a lot faster. For example:

#!/usr/bin/perl
use strict;
use warnings;
use Test::More 0.88;
BEGIN { use_ok 'MIME::Base64' => qw(encode_base64) }

is( encode_base64("test", "dGVzdA==", q{"test" encodes okay} );
done_testing;

Run that script, with perl or with prove, and it won't just tell you that it didn't match, it will say:

#   Failed test '"test" encodes okay'  
#   at testbase64.pl line 6.
#          got: 'gGVzdA==
# '
#     expected: 'dGVzdA=='

and sharp-eyed readers will notice that the difference between the two is indeed the newline. :)

hobbs