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

Hello ,monks.
I have this text file:
I'll put numbers to it's lines.
1. Start context.
2. Some entry.
3. End context.
4. Start context.
5. Some different entry.
6. End context.

I try to eliminate the text in such way that the entry
between the closest START and END entries will be deleted.
The problem is that my script takes the first "Start
context" and goes trough the file until the last "End
context".

Here's a sample of what I use:
$ARGV[0]=$commandfile; $^I=".bak"; while(<>) { foreach $com (keys %hashnew) { if (/$hashnew{com}/../\*\ Exit\ conte +xt\ \*/) { s/$com//; } } print WFILE $_; }
What should I do.
Thank you very much.

Edited by Chady -- code tags.

Replies are listed 'Best First'.
Re: File parsing-again
by heroin_bob (Sexton) on Jun 30, 2004 at 15:07 UTC
    I stumbled upon this type of problem the other day while perusing through the tutorials section. Chromatic covers this nicely in the common regex gotchas article on greediness. It's sure saved me hours of hairpulling...


    If you're ever lost and need directions, ask the guy on the motorcycle.
Re: File parsing-again
by Aragorn (Curate) on Jun 30, 2004 at 15:06 UTC
    Maybe this helps:
    #!/usr/local/bin/perl use strict; use warnings; my @ctx_starters = qw(start1 start3); while (my $line = <DATA>) { if (grep { $line =~ /$_/ } @ctx_starters) { print $line; INNER: while ($line = <DATA>) { next INNER if $line !~ /^end/; print $line; last INNER; } } else { print $line; } } __DATA__ start1 foo bar end start2 baz quux end start3 bla bla end start4 hmm end start5 last one here end
    Arjen