1

This question is related to Perl, writing array to a text file.

I open a filename_1 and store the content of this file to an array. Then I write this array to the filename_2. If I don't modify this array. I expect that the filename_2 is exactly the same as the filename_1.

Instead, I see an extra line at the end of filename_2. Can someone help me?

Here is my code:

open( Fh, "<", "filename_1.txt") or die "Cannot open for read";
my @l_file_content_array = <Fh>;
close Fh;

open( Fh2, ">", "filename_2.txt") or die "Cannot open for write";
print Fh2 @l_file_content_array;
close Fh2;
3
  • Those files should be the same... when you diff them, what is the difference? Commented Dec 15, 2015 at 1:58
  • The difference is that there is an extra line a the end of the filename_2. The indication of this difference can be seen by the location of the cursor when you open both files. Or the cvs software or other diff software will point out this difference. Commented Dec 15, 2015 at 16:58
  • Works fine in Perl 5.20 on Ubuntu 14.10. What system are you using? Commented Dec 17, 2015 at 9:03

2 Answers 2

2

Try adding the line:

$\ = ""; # set default print ending to empty string

before the print Fh2 @l_file_content_array; line.

If the above "works" it may mean that there is a

$\ = "\n";

line somewhere else in the program or included file. You can still fix the behavior locally by adding the line:

local $\ = "";
Sign up to request clarification or add additional context in comments.

Comments

-1

You can try:

chomp(my @l_file_content_array = <Fh>);

It supposed to remove the final line end of your input file.

2 Comments

Thanks for your response. However, this suggestion does not not work. Using the code with chomp above, the filename_2 then contains only a single line that has the content of filename_1. All lines of filename_1 has the \n removed and concatenated into a single line.
@user5680155 Yeah, I'd think you can use print Fh2 join("\n", @l_file_content_array); instead of print Fh2 @l_file_content_array; However, if you are not agree with this, you can use my @contents = <FH>; chomp($contents[$#contents]); that will remove the last line end of your file.

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.