How can I print a matching line, one line immediately above it and one line immediately below?

后端 未结 8 1083
你的背包
你的背包 2020-12-16 07:23

From a related question asked by Bi, I\'ve learnt how to print a matching line together with the line immediately below it. The code looks really simple:

#!p         


        
8条回答
  •  感动是毒
    2020-12-16 08:20

    Here's a modernized version of Pax's excellent answer:

    use strict;
    use warnings;
    
    open( my $fh, '<', 'qq.in') 
        or die "Error opening file - $!\n";
    
    my $this_line = "";
    my $do_next = 0;
    
    while(<$fh>) {
        my $last_line = $this_line;
        $this_line = $_;
    
        if ($this_line =~ /XXX/) {
            print $last_line unless $do_next;
            print $this_line;
            $do_next = 1;
        } else {
            print $this_line if $do_next;
            $last_line = "";
            $do_next = 0;
        }
    }
    close ($fh);
    

    See Why is three-argument open calls with lexical filehandles a Perl best practice? for an discussion of the reasons for the most important changes.

    Important changes:

    • 3 argument open.
    • lexical filehandle
    • added strict and warnings pragmas.
    • variables declared with lexical scope.

    Minor changes (issues of style and personal taste):

    • removed unneeded parens from post-fix if
    • converted an if-not contstruct into unless.

    If you find this answer useful, be sure to up-vote Pax's original.

提交回复
热议问题