in reply to Processing lines after a pattern in a while loop

NovMonk,
This is fairly common task. Often what is desired is to only do something between two lines within a file. I often recommend using an off/on flag.
my $flag = 0; while ( <INPUT> ) { chomp; if ( /pattern/ ) { $flag = 1; next; } next if ! $flag; # what you want to do goes here }
Cheers - L~R

Replies are listed 'Best First'.
Re: Re: Processing lines after a pattern in a while loop
by tilly (Archbishop) on Apr 05, 2004 at 17:47 UTC
    Red flag alert!

    Do not name flags $flag. If you give flags such meaningless names, then one of the more common errors in your code will be that you accidentally reverse the meaning of a flag.

    Instead give flags names which are yes/no questions, which the flag's value is an answer to. Now you'll never have trouble keeping it straight, and nor will anyone else who glances at your code.

    If you think this advice is silly, then remind yourself of it the next time you catch a bug due to your accidentally reversing a flag's meaning...

Re: Re: Processing lines after a pattern in a while loop
by talexb (Chancellor) on Apr 05, 2004 at 17:58 UTC

    To echo what tilly said, don't use 'flag' for a variable name unless you're talking about a square or rectangle of cloth. Why not something more interesting like $seenJunkYet instead?

    I'd rather go for something like

    # Skip header junk while(<>) { last if /end of header junk/; } # Start processing real data while(<>) { # But quit if we see junk starting up again last if /start of trailer junk/; # Do useful stuff here }
    That way there aren't any flag variables. It's more lines of code, but it reads more easily.

    Alex / talexb / Toronto

    Life is short: get busy!

Re: Re: Processing lines after a pattern in a while loop
by Happy-the-monk (Canon) on Apr 05, 2004 at 16:49 UTC