Why does this comparison of base64 strings in Perl fail?

I am trying to compare encode_base64('test') with a string variable containing the base64 string of 'test'. The problem is that he never checks!

 use MIMI::Base64 qw(encode_base64); if (encode_base64("test") eq "dGVzdA==") { print "true"; } 

Did I forget something?

+4
source share
3 answers

Here is a link to the Perlmonks page that says: "Beware of the new line at the end of encoded lines encode_base64 ().

Thus, a simple "eq" may fail.

To suppress a new line, say encode_base64("test", "") .

+10
source

When you are comparing strings, and this happens unexpectedly, print the strings to see what is actually in them. I put brackets around the value to see extra spaces:

 use MIME::Base64; $b64 = encode_base64("test"); print "b64 is [$b64]\n"; if ($b64 eq "dGVzdA==") { print "true"; } 

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

In addition, sometimes you need to read the documentation for things a couple of times to catch important parts. In this case, MIME :: Base64 tells you that encode_base64 takes two arguments. The second argument is a line ending and is used by default for a new line. If you do not need a new line at the end of the line, you need to give it another line, for example an empty line:

 encode_base64("test", "") 
+8
source

Here's an interesting tip: use Perl's wonderful and favorite testing modules for debugging. This will not only give you the opportunity to start testing, but sometimes they will significantly speed up the debugging process. For instance:

 #!/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 the script with perl or with prove , and it will not just tell you that it does not match, it will say:

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

and readers with sharp eyes will notice that the difference between them is indeed a new line. :)

0
source

All Articles