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

后端 未结 7 2576
一向
一向 2021-02-20 12:22

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

相关标签:
7条回答
  • 2021-02-20 13:04

    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";
        }
    '
    
    0 讨论(0)
  • 2021-02-20 13:08

    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]
    
    0 讨论(0)
  • 2021-02-20 13:12

    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
    0 讨论(0)
  • 2021-02-20 13:14

    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);
    
    0 讨论(0)
  • 2021-02-20 13:18

    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";
    
    0 讨论(0)
  • 2021-02-20 13:22
    #!/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;
    
    0 讨论(0)
提交回复
热议问题