Since I'm feeling generous and it's late on a Friday afternoon so nobody is touching prod, here's a tidy-up and fix for you. The steps were as follows:
- Add strict and warnings. Just because this was originally a section of longer code doesn't mean you cannot or should not use them here.
- Fix up any contraventions of strict arising.
- Remove unreferenced variables.
- Shorten the code with postfix loops and de-duplicated elif branches. Simply the regexen while there.
- Run it through perltidy to fix the indenting.
- At this point it's clear where the problem is. Apply a simple fix (which is basically a version of choroba's solution).
#!/usr/bin/perl
use strict;
use warnings;
my @lines = (
't13:45\n', 'D13:45\n',
'S13:45 Unicorn\n', 'D13:45\n',
'S13:45\n', 'T13:45\n',
't13:45\n', 'D13:45\n',
'T13:46\n', 't13:45\n',
'D13:45\n', 'S13:45\n',
'D13:45\n', 'S13:45 UNICORN\n',
'T13:45\n', 't13:45\n',
'D13:45\n', 'T13:46\n'
);
my $value = "unicorn";
my $newsection = 0;
my $debug = 0; # Set to 1 for verbosity
my @section;
print "Let's start\n" if $debug;
while (my $row = shift (@lines)) {
if ($newsection <= 0) {
if ($row =~ /^t/) {
print "New section started\n" if $debug;
print "Inserting $row into array\n" if $debug;
push (@section, $row);
} elsif ($row =~ /^[JSD]/) {
print "Section continued\n" if $debug;
push (@section, $row);
} elsif ($row =~ /^T/) {
print "Section Ended\n" if $debug;
push (@section, $row);
$newsection = 1;
}
}
if ($newsection > 0) {
$newsection = 0;
print "Checking for value\n" if $debug;
if (grep (/$value/i, @section)) {
print "Value discovered, saving section\n" if $debug;
print "$_\n" for @section;
}
@section = ();
}
}
Running this we get:
t13:45\n
D13:45\n
S13:45 Unicorn\n
D13:45\n
S13:45\n
T13:45\n
t13:45\n
D13:45\n
S13:45\n
D13:45\n
S13:45 UNICORN\n
T13:45\n
... which I can only presume is what you expect the output to be. Enjoy.