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

后端 未结 7 2475
一向
一向 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:24

    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() { 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 = ;
    

    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 = ; # (2)
    close(F);
    chomp(@lines);
    
    print "@lines"; # (3) stringify
    

提交回复
热议问题