Perl read line by line

后端 未结 5 1960
Happy的楠姐
Happy的楠姐 2020-11-29 00:10

I have a simple Perl script to read a file line by line. Code is below. I want to display two lines and break the loop. But it doesn\'t work. Where is the bug?



        
5条回答
  •  情深已故
    2020-11-29 00:40

    If you had use strict turned on, you would have found out that $++foo doesn't make any sense.

    Here's how to do it:

    use strict;
    use warnings;
    
    my $file = 'SnPmaster.txt';
    open my $info, $file or die "Could not open $file: $!";
    
    while( my $line = <$info>)  {   
        print $line;    
        last if $. == 2;
    }
    
    close $info;
    

    This takes advantage of the special variable $. which keeps track of the line number in the current file. (See perlvar)

    If you want to use a counter instead, use

    my $count = 0;
    while( my $line = <$info>)  {   
        print $line;    
        last if ++$count == 2;
    }
    

提交回复
热议问题