jhuijsing has asked for the wisdom of the Perl Monks concerning the following question:

With the following code

open( IP_FH, "test.txt" ); while (<IP_FH>) { if ( /ABCD/ ... /EFGH/ ) { $match = 1; $found .= $_; } else { if ( $match ) { $match = 0 ; print "========\n"; print $found; $found = (); } } }

and the test.txt file contains script works as expected

ABCD 122132 12 312 EFGH FRED ABCD sadasd asd das EFGH FRED ABCD asdasd d as EFGH

but when test.txt contains the text below it fails

ABCD 122132 12 312 EFGH ABCD sadasd asd das EFGH ABCD asdasd d as EFGH

Replies are listed 'Best First'.
Re: Perl Range operator question
by ikegami (Patriarch) on Jul 08, 2010 at 05:18 UTC

    The flip-flop operator returns a special value when the flop condition is true. Take advantage of it to determine that it's time to process what you have accumulated.

    my $found; while (<>) { my $i = /ABCD/ ... /EFGH/; if ($i) { $found .= $_; if ($i =~ /E/) { print "========\n"; print $found; $found = ''; } } }

    You can also achieve the same with the following:

    while (<>) { my $i = /ABCD/ ... /EFGH/; print "========\n" if $i == 1; print if $i; }
Re: Perl Range operator question
by jwkrahn (Abbot) on Jul 08, 2010 at 05:08 UTC

    The else clause of your if statement will never execute if ABCD immediately follows EFGH.    Try it like this instead:

    open IP_FH, '<', 'test.txt' or die "Cannot open 'test.txt' $!"; my ( $match, $found ); while ( <IP_FH> ) { if ( /ABCD/ ... /EFGH/ ) { $match = 1; $found .= $_; } if ( $match ) { $match = 0 ; print "========\n"; print $found; $found = ''; } }

      Thanks for the responses Problems you find when you try to reuse code. That I wrote 7 years, when I first started to use Perl.

Re: Perl Range operator question
by afoken (Chancellor) on Jul 08, 2010 at 04:56 UTC
    • Explain "fails". What happens, what do you expect to happen instead?
    • Add use strict; use warnings; to your code.
    • Add error checks to your code (open ... or die "... $!" or use autodie qw(:all);).

    Alexander

    --
    Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)