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
This is the simplest version I could come up with:
perl -l040 -pe';' < test.txt
Which is roughly equivalent to:
perl -pe'
chomp; $\ = $/; # -l
$\ = 040; # -040
'
and:
perl -e'
LINE:
while (<>) {
chomp; $\ = $/; # -l
$\ = " "; # -040
} continue {
print or die "-p destination: $!\n";
}
'
This is the code that do this (assume the below code inside script.pl) :
use strict;
use warnings
my @array = <> ;
chomp @array;
print "@array";
It is run by:
scirpt.pl [your file]
Here is my single liner:
perl -e 'chomp(@a = <>); print join(" ", @a)' test.txt
Explanation:
@a
arraychomp(..)
- remove EOL symbols for each line@a
using space as separatorOne 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);
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";
#!/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;