Ellen Ellen - 6 months ago 29
Perl Question

Read newline delimited file in Perl

I am trying to read a newline-delimited file into an array in Perl. I do NOT want the newlines to be part of the array, because the elements are filenames to read later. That is, each element should be "foo" and not "foo\n". I have done this successfully in the past using the methods advocated in Stack Overflow question Read a file into an array using Perl and Newline Delimited Input.

My code is:

open(IN, "< test") or die ("Couldn't open");
@arr = <IN>;
print("$arr[0] $arr[1]")


And my file 'test' is:

a
b
c
d
e


My expected output would be:

a b


My actual output is:

a
b


I really don't see what I'm doing wrong. How do I read these files into arrays?

Answer

Here is how I generically read from files.

open (my $in, "<", "test") or die $!;
my @arr;

while (my $line = <$in>) {
  chomp $line;
  push @arr, $line;
}

close ($in);

chomp will remove newlines from the line read. You should also use the three-argument version of open.