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

后端 未结 8 1053
你的背包
你的背包 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:12

    You always want to store the last line that you saw in case the next line has your pattern and you need to print it. Using an array like you did in the second code snippet is probably overkill.

    my $last = "";
    while (my $line = ) {
      if ($line =~ /Pattern/) {
        print $last;
        print $line;
        print scalar ;  # next line
      }
      $last = $line;
    }
    

提交回复
热议问题