use strict; # first slurp the file my $content = do { local $/; open my $fh, "<", "in.txt" or die $!; <$fh> }; # then split it into chunks my @chunks = $content =~ /##Flag##(.*?)##CloseFlag##/sg; # now analyze the chunks for my $chunk (@chunks) { my ($first, $last) = $chunk =~ /T:(\d+).*?(\d+)\D*$/s; # count number of newlines my $newlines = $chunk =~ tr/\n/\n/; print "first-last: ", $first - $last, "# of lines: ", $newlines-1, "\n"; }