A Perl array chomp example

Summary: How to use the Perl array chomp syntax to chomp every element in a Perl array.

I just ran into a weird situation where a file I read into a Perl array was messed up, and some lines in the file had one form of "newline" character, and other parts of the file had some other type of newline character(s). The file looked fine in vi (even when I used "vi -b" to look at it), but if I read it in and spit it out with Perl, part of the output lines were messed up, and they all ended up printing as one long line.

Perl array chomp to the rescue

To fix this problem I just did a Perl chomp on the array, and then manually added a newline character back in during my print process.

In the first step of my process, the source code to read a file into a Perl array looks like this:

open(INPUT_FILE,$sourceFileName);
my @srcFileContents = (<INPUT_FILE>);
close(INPUT_FILE);

and then once I had the file contents in the @srcFileContents array, the new code to chomp the Perl array looks like this:

# chomp the perl array
chomp(@srcFileContents);

And finally the new code to print the chomp'd Perl array looks like this:

foreach $rec (@srcFileContents) {
  print OUTPUT_FILE "$rec\n";
}

With this new "Perl array chomp" approach, this new code works just fine now; all the output lines have one and only one newline character, the one I added back in manually.

Before the Perl array chomp - What didn't work

For some reason the Perl array code that didn't work looked like this:

# read the file into the array
open(INPUT_FILE,$sourceFileName);
my @srcFileContents = (<INPUT_FILE>);
close(INPUT_FILE);

# print the records from the input file
print OUTPUT_FILE @srcFileContents;

I don't know exactly why this approach worked for some lines and not for others, and I don't particularly care. As I mentioned at the beginning of this article, my assumption is that there is something wrong with the input files, where some lines have one type of newline character, and the other lines have a different type of newline character.

Happily, the Perl array chomp code shown above fixed the problem with the extra file characters, and at the moment I don't really care what type of characters they were, the Perl chomp function took care of them.