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

Hi Monks,

I am reading in a text file (that I am free to edit) which contains lines of either text or numbers. As I read in, line by line, I push the line into @numbers or @text, as appropriate. I am using both strict and warnings.

My question concerns handling of "\n" in the input file. In one of the lines of text in the file, I find the string:

"some text here \n some text here."

When I look at @text after I am done with the file, that array element reads:

"some text here \\n some text here."

I've pinpointed the change to the following snippet of code surrounded by Dumper calls:

if ($x>=2 && $line !~ /^Text/) { $string .= $line; print "In 'if, line ne text', string is:\n$string\n"; $x++; next; } if ($x!=0){ push (@texts, $string); # whether I use this line or the one afte +r, the result is the same # $texts[$i] = $string; print "In if, using push, \@texts is:\n"; print Dumper(@texts), "\n"; $string = ''; $i++; $x = 0; goto TT; }

The output is, as mentioned above:

In 'if, line ne text', string is: some text here\n some text here In if, using push, @texts is: $VAR1 = 'some text here.'; etc... $VAR10 = 'some text here.\\n some text here.';

So, my question is, why is the newline character having an extra escape character added to it when I push it into @texts, and how do I keep the \n but remove the extra '\'?

Thanks!

Replies are listed 'Best First'.
Re: Escape character being escaped in array push
by cavac (Prior) on Apr 04, 2022 at 21:44 UTC

    Because the text in the file is not a newline character. It's a backslash plus the character "n".

    When you use Data::Dumper to print out a variable, it tries to escape all characters that need escaping to make it a valid string usable in Perl source code. As a Backslash would be used in a string as escape character, it needs escaping (double backslash), in order to produce a string that represents the original text (e.g. a backslash and the character "n").

    You can check this with a hex editor (or "hexdump -C" on Linux) on the original text file.

    perl -e 'use Crypt::Digest::SHA256 qw[sha256_hex]; print substr(sha256_hex("the Answer To Life, The Universe And Everything"), 6, 2), "\n";'

      Oh my god, I'm such an idiot.

      Thank you. My confusion was a cross between this brain fart and forgetting how to properly use the find and replace all in BBEdit. Oof. Thanks for the memory jolt.