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 print the lines like this:
line1 line2 line3
But how can I do this?
In Java, we can store the content of the file into an array either by reading the file using a scanner or bufferedReader or FileReader or by using readAllLines method.
A string can be converted into an array using the split() function. @ARRAY = split (/REGEX/, $STRING); Where: @ARRAY is the array variable that will be assigned the resulting array.
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 separator#!/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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With