bugbuster has asked for the wisdom of the Perl Monks concerning the following question:

I am having a strange problem while using the Crypt::CBC module. First i wrote a simple test script that encodes and decodes using Crypt::CBC and 'Blowfish'. I encrypted a file and then decrypted the encrypted file. The resulting file was the same as the original file. I then wrote another version of my test script which attempted to decrypt a file and then use the "split" function to break the decrypted data into an array of lines. Although all the data was correctly decrypted, the split function only generated 1 line, not the correct number of lines. Here is the relevant code lines.

use strict; use warnings; use Crypt::CBC; my $cipher; $cipher = Crypt::CBC->new( -key => $secret_key, -cipher => 'Blowfish' ); local $/; unless ( open(INPUT,"<$filename") ) { die("open failed for file '$filename' : $!\n"); } # UNLESS $data = <INPUT>; close(INPUT); $decrypted = $cipher->decrypt($data); @lines = split(/\r\n/,$decrypted); $num_lines = split(/\r\n/,$decrypted);

When I ran the script, the data was correctly decrypted, however the split() function only generated one big line. Why did I not get the correct number of lines ? I am running on a windows 7 laptop using perl 5.16.3

Replies are listed 'Best First'.
Re: problem with Crypt::CBC
by blindluke (Hermit) on Nov 10, 2014 at 12:55 UTC

    My quick guess would be: try splitting by "\n". Perl should be smart enough to figure out that it's actually two characters. So, try this:

    @lines = split(/\n/,$decrypted);

    And in case you are wondering why this should work, here is an explanation of the details.

    UPDATE:

    Another suggestion - there is no need to run split twice, this is enough:

    @lines = split(/\n/,$decrypted); $num_lines = @lines;

    Now, when you modify the split regexp, you only have to do it in one place.

    Good luck with your project, and welcome to the Monastery.

    - Luke

Re: problem with Crypt::CBC
by karlgoethebier (Abbot) on Nov 10, 2014 at 13:12 UTC

    blindluke guessed it already, but anyway, a short look at perlrebackslash:

    "\n matches a logical newline. Perl converts between \n and your OS's native newline character when reading from or writing to text files."

    Your newline character is CRLF. But you don't need to care about because Perl does already ;-)

    Regards, Karl

    «The Crux of the Biscuit is the Apostrophe»