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.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.