Perl read line by line

后端 未结 5 1962
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:48

    With these types of complex programs, it's better to let Perl generate the Perl code for you:

    $ perl -MO=Deparse -pe'exit if $.>2'
    

    Which will gladly tell you the answer,

    LINE: while (defined($_ = )) {
        exit if $. > 2;
    }
    continue {
        die "-p destination: $!\n" unless print $_;
    }
    

    Alternatively, you can simply run it as such from the command line,

    $ perl -pe'exit if$.>2' file.txt
    

提交回复
热议问题