Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read the lines of a file into an array in Perl?

Tags:

file-io

perl

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?

like image 842
Nathan Campos Avatar asked Dec 09 '09 22:12

Nathan Campos


People also ask

How do you read an array of files?

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.

How do I convert a string to an array in Perl?

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.


2 Answers

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
like image 94
Ivan Nevostruev Avatar answered Oct 03 '22 14:10

Ivan Nevostruev


#!/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;
like image 21
Corey Avatar answered Oct 03 '22 12:10

Corey