2

I am trying to concatenate 3 strings in perl, and I am getting weird behavior. The data was just written to a file previously in the script, and I am trying to add two columns to the data.

Here is my code and its behavior

print "phylipId is $phylipId\n";
print "Tree is $tree\n";
print "Line is $line\n";

my $string = join "\t", $phylipId, $tree, $line;

print "Concatenated is $string\n";

Gives me this output

phylipId is 4
Tree is (138,((139,141),140));
Line is 000931  17.0    1.0 0.135   no  1044    646918204
Concaten000931s 17.0    1.08,((10.1351),no0));  1044    646918204

This also happened when I used the . operator. Any help would be appreciated

3 Answers 3

4

It looks like youre reading $tree from a file using carriage-returns (\r), and $tree is ending up with \r at the end of it causing it to seek to the beginning of the line.

See this test:

perl -e 'print("abcdefghijkl\r\t012\n");'

Which outputs

abcdefgh012l
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, this was the problem. I was generating the tree files using a template file that had been created in windows. I fixed the line endings for them and it works now, thanks
1

As patrick says, it is more than likely you have read a DOS-formatted file on a Linux box. In those circumstances, if you use chomp on a string terminated with "\r\n" you will be left with the "\r".

The simplest way to clean up records like this is to replace chomp with

s/\s+$//

which, since both "\r" and "\n" count as whitespace, will remove both from the string simultaneously. If trailing tabs and spaces are important for you then use

s/[\r\n]+$//

instead, or perhaps

s/[[:cntrl:]]+$//

or

s/\p{Control}+$//

2 Comments

If the file is known to have "\r\n" line endings, the clean way to so this is to set $/ = "\r\n" and then use chomp.
@Patrick: My intention was to offer something that would work on all files regardless of origin, but you are absolutely right and that is what I would write.
0

I'm not able to replicate your issue after trying under Windows and Linux.

  • Could the issue be related to how your console is configured?
  • does it happen on other machines too?
  • Can you tell more about your exact environment?
  • What happens if you try to print that line to a text file instead of stdout?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.