Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: Cannot find the error

by hippo (Chancellor)
on Apr 03, 2020 at 16:00 UTC ( #11114998=note: print w/replies, xml ) Need Help??


in reply to Cannot find the error

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://11114998]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (9)
As of 2020-06-01 17:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you really want to know if there is extraterrestrial life?



    Results (5 votes). Check out past polls.

    Notices?