How can I read the lines of a file into an array in Perl?
Solution 1
#!/usr/bin/env perl
use strict;
use warnings;
my @array;
open(my $fh, "<", "test.txt")
or die "Failed to open file: $!\n";
while(<$fh>) {
chomp;
push @array, $_;
}
close $fh;
print join " ", @array;
Solution 2
Here is my single liner:
perl -e 'chomp(@a = <>); print join(" ", @a)' test.txt
Explanation:
- read file by lines into
@a
array -
chomp(..)
- remove EOL symbols for each line - concatenate
@a
using space as separator - print result
- pass file name as parameter
Solution 3
If you find yourself slurping files frequently, you could use the File::Slurp module from CPAN:
use strict;
use warnings;
use File::Slurp;
my @lines = read_file('test.txt');
chomp @lines;
print "@lines\n";
Solution 4
The most basic example looks like this:
#!/usr/bin/env perl
use strict;
use warnings;
open(F, "<", "test.txt") or die("Cannot open test.txt: $!\n"); # (1)
my @lines = ();
while(<F>) { chomp; push(@lines, $_); } # (2)
close(F);
print "@lines"; # (3) stringify
(1) is the place where the file is opened.
(2) File handles work nicely within list enviroments (scalar/list environments are defined by the left value), so if you assign an array to a file handle, all the lines are slurped into the array. The lines are delimited (ended) by the value of $/
, the input record separator. If you use English;
, you can use $IRS
or $INPUT_RECORD_SEPARATOR
. This value defaults to the newline character \n
;
While this seemed to be a nice idea, I've just forgot the fact that if you print all the lines, the ending \n
will be printed too. Baaad me.
Originally the code was:
my @lines = <F>;
instead of the while
loop. This is still a viable alternative, but you should swap (3) with chomp
ing and then printing/stringifying all the elements:
for (@lines) { chomp; }
print "@lines";
(3) Stringifying means converting an array to a string and inserting the value $"
between the array elements. This defaults to a space.
See: the perlvar page.
So the actual 2nd try is:
#!/usr/bin/env perl
use strict;
use warnings;
open(F, "<", "test.txt") or die("Cannot open test.txt: $!\n"); # (1)
my @lines = <F>; # (2)
close(F);
chomp(@lines);
print "@lines"; # (3) stringify
Solution 5
One more answer for you to choose from:
#!/usr/bin/env perl
open(FILE, "<", "test.txt") or die("Can't open file");
@lines = <FILE>;
close(FILE);
chomp(@lines);
print join(" ", @lines);
Nathan Campos
Electrical Engineer, Ham radio operator, photographer, used to be a programmer.
Updated on July 09, 2022Comments
-
Nathan Campos almost 2 years
I have a file named test.txt that is like this:
Test
Foo
BarBut I want to put each line in a array and print the lines like this:
line1 line2 line3
But how can I do this?
-
Ether over 14 years+1 for strictures, lexical filehandles and the 3-arg
open
. :) -
Ivan Nevostruev over 14 yearsYou should check if file was opened successfully. Always. Or
use autodie;
-
Ivan Nevostruev over 14 yearsThere is shortcut for chomp:
chomp(@lines);
-
Greg Bacon over 14 years
perl -le 'chomp(@a=<>); print "@a"' file ..
-
Ivan Nevostruev over 14 years@gbacon: Thanks for shorter version
-
Tamas Mezei over 14 yearsOh, I forgot that. Thanks for the tip, Ivan!
-
Echelon over 6 yearsThank you. I've never seen that shorthand way of loading and chomping an array at the same time before.