Nathan Campos
Nathan Campos

Reputation: 29497

How can I read the lines of a file into an array in 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?

Upvotes: 11

Views: 57535

Answers (7)

dan
dan

Reputation: 905

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]

Upvotes: 1

Brad Gilbert
Brad Gilbert

Reputation: 34120

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";
    }
'

Upvotes: 1

Tamas Mezei
Tamas Mezei

Reputation: 899

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 chomping 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

Upvotes: 2

Corey
Corey

Reputation: 1542

#!/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;

Upvotes: 24

toolic
toolic

Reputation: 62037

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";

Upvotes: 2

Ivan Nevostruev
Ivan Nevostruev

Reputation: 28713

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

Upvotes: 17

Mark Byers
Mark Byers

Reputation: 838156

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);

Upvotes: 2

Related Questions