Problem with unwanted newline

  • Thread starter Andrew R. Gillett
  • Start date
A

Andrew R. Gillett

Being a Perl newbie, I may be doing something very simple wrong here. The
following line doesn't seem to work as I expect it to:

print FILEHANDLE 'Thing:\n' . $var1 . '\n' . $var2;


The desired output (if var1 = Hello and var2 = Goodbye) is:

Thing:\nHello\nGoodbye


But what I actually get is this:

Thing:\nHello
\nGoodbye


The most likely explanation is that var1 has a newline in it (the text is
read in from a file). I tried stripping \n from the variable, it didn't
work but I'm not sure if this is the right way to do it:

$var1 =~ s/"\n"//;
 
G

gnarred

You can write the first line as:

print FILEHANDLE "Thing:\\n$var1\\n$var2";

Note that \\ tells perl "I want a real slash, I don't want to escape a
character", and the quotes "" will automatically expand variables
contained within (but you already knew that)

You're right, $var1 seems to have a newline at it's end, so you can:

chomp($var1); # nix the newline

Your regular expression doesn't work because perl treats the quote in
the regex literally. Your regex will match a quote followed by a
newline followed by a quote. You should write it as:

s/\n//;

A regular expression expands variables & escapees just like double
quotes do. So, with your vars below:

$str =~ s/$var1/$var2/;

Will replace the first occurance of Hello in $str with Goodbye


gnarred
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top