I'm trying to split a file into multiple files based on lines START and END from the input file. The below code does it fine, but, it is not writing into the output file inside the loop.
use strict;
use warnings;
open my $fh_i, "<", "input.txt" or die $!;
my $in_block = 0;
my $counter = 0;
my $filename = "output_1.txt";
while( <$fh_i> ) {
$in_block = 0 if /^END/;
open (my $fh_o, ">", $filename) or die $!;
print $fh_o $_ if $in_block; #Issue line
if /^START/
{
close $fh_o;
$in_block = 1 ;
$counter = $counter + 1;
$filename = "output_".$counter.'.txt';
}
}
close $fh_i;
I think the $_ is losing the data when the file is opened. #Issue line is what am worried about. It isn't writing into the file. The files are all empty. What am I missing here?
Sample data in the input file:
START1
line1
line2
line3
END1
START2
line1
line2
line3
END2
START3
line1
END3
Expected result.
output_1.txt should have the below.
START1
line1
line2
line3
END1
output_2.txt should have the below.
START2
line1
line2
line3
END2
output_3.txt should have the below.
START3
line1
END3