For Programmers: Free Programming Magazines  


Home > Archive > PERL Beginners > December 2007 > Question about escaped characters









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Question about escaped characters
Why Tea

2007-12-12, 8:00 am

my $s = "This is a string\nThis is line 2\n";
print $s;

The "\n" is interpreted as newline in the code above. But if the
string (i.e. $s) is in a file, it will be printed literally as "\n" -
how do I get Perl to treat it as newline?

/Why Tea

Chas. Owens

2007-12-12, 8:00 am

On Dec 11, 2007 7:33 PM, Why Tea <ytlim1@gmail.com> wrote:
> my $s = "This is a string\nThis is line 2\n";
> print $s;
>
> The "\n" is interpreted as newline in the code above. But if the
> string (i.e. $s) is in a file, it will be printed literally as "\n" -
> how do I get Perl to treat it as newline?
>
> /Why Tea

snip

I can think of two ways off the top of my head: an evil one and a pita one.

The painful one is to use a substitution on the string to change all
occurrences of '\n' with "\n":

$s =~ s/\\n/\n/g;

Of course, this won't do the right thing for '\\n' (i.e. where you are
escaping the escape, not the n), so you have to run this substitution
first

$s =~ s/\\\\/\\/g;
$s =~ s/\\n/\n/g;

Of course, this only handles "\n", you would also need to add a
substitution for "\t", "\r", etc. I won't go into the evil one, but
lets just say string eval is highly insecure (especially in a CGI
program).
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com