ybiC has asked for the wisdom of the Perl Monks concerning the following question:

This post was moved to How to populate array with lines from text file? (Moved from Q&A).
Please post your answers there.

Thank you -- Q&AEditors

Originally posted as a Categorized Question.

  • Comment on how to populate array with lines from text file?

Replies are listed 'Best First'.
Answer: how to populate array with lines from text file?
by mirod (Canon) on Dec 08, 2000 at 17:23 UTC

    The simplest way is probably:

    my @lines=<FH>;
Answer: how to populate array with lines from text file?
by jreades (Friar) on Dec 08, 2000 at 21:03 UTC

    Or you can just do this:

    open(FILE, "<" . $file) or die ("Can't open file: $!"); my @lines = <FILE>; close FILE;
Answer: how to populate array with lines from text file?
by Anonymous Monk on Dec 08, 2000 at 18:12 UTC
    This is quite easy:
    1 #!/usr/bin/perl -w 2 use strict; 3 4 $file = "/path/file"; 5 open (<FH>, "< $file") or die "Can't open $file for read: $!"; 6 my @lines = <FH>; 9 close FH or die "Cannot close $file: $!"; 10
    Regards Jens
Answer: how to populate array with lines from text file?
by t0mas (Priest) on Dec 08, 2000 at 18:15 UTC
    my @lines=do{local @ARGV='/path/file';<>};
      Of all ways to put a file's lines in an array, I'm afraid that is one of the most inefficient. Moving data from INSIDE a do { } block to OUTSIDE a do { } block requires copying it, so you're making a list and checking it twice, so to speak.

      If I REALLY needed to put a file into an array (why, I do not know), using the above trick, I'd do:
      my @lines; { local @ARGV = $file; @lines = <> }
      But why should the file be in an array? Ick.

      japhy -- Perl and Regex Hacker
Answer: how to populate array with lines from text file?
by marvell (Pilgrim) on Dec 08, 2000 at 19:32 UTC
    A nice simplification would be:

    my @lines = <FH>;

Answer: how to populate array with lines from text file?
by ybiC (Prior) on Dec 08, 2000 at 17:57 UTC
    Ooot.   Page 92 of the Ram says it all - chomp and $_.
    Mutter, mutter... too many books stacked on my desk... mumble, mumble...
    1 #!/usr/bin/perl -w 2 use strict; 3 4 $file = "/path/file"; 5 @lines = (); 6 open (<FH>, "< $file") or die "Cannot open $file for read: $!"; 7 while (<FH>) { 8 chomp; 9 push (@lines, $_); 10 } 11 close FH or die "Cannot close $file: $!"; 12 13 print join(',', @lines); # now it works