I have a file named test.txt that is like this:
Test
Foo
Bar
But I want to put each line in a array and pri
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