Search code examples
perlflip-flopchomp

Connecting rows in Perl after filter


I want ask you for some tips. My code looks like next few rows:

#!/usr/bin/env perl

while (<DATA>) {
 if (/\bSTART\b/ .. /\bEND\b/) {
    #$together = $_;
    #$together = chomp ($_);  
    print ($_, "\n");   
 }
}

__DATA__
rubish
rub
START Data Data Data start 15.05.2015 Data i want end Data 
END
rubishend

*****************
example:
START new line 1 line 2new line 3 END
*****************

My goal is to filter many line log. Output is one or two lines matching regex. But output can be one-line --> It´s what I want. Or two-line, in this case I need to join second line to the end of first. Output from my code looks like:

START Data Data Data start 15.05.2015 Data i want end Data 
END
START new line 1 line 2new line 3 END

What I want is:

START Data Data Data start 15.05.2015 Data i want end Data END
START new line 1 line 2new line 3 END

Any tips how to distinguish two line output and connect it into one line? For better parsing in next steps? Thanks for answer


Solution

  • From flip-flop operator's documentation:

    The value returned is either the empty string for false, or a sequence number (beginning with 1) for true. [...] The final sequence number in a range has the string "E0" appended to it

    So,

    while (<DATA>) {
       if (my $i = /\bSTART\b/ .. /\bEND\b/) {
          s/\n/ / if $i !~ /E0\z/; 
          print;
       }
    }
    

    Without the flip-flop operator:

    my $in = 0;
    while (<DATA>) {
       if ($in ||= /\bSTART\b/) {
          if (/\bEND\b/) {
             $in = 0;
          } else {
             s/\n/ /;
          }
          print;
       }
    }