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

Hello Great Monks,

I am writing a filter file to filter out some lines from two file and then compare them. Basically, I am using regular expressions to check for a line I want to be remove and then return 0 for such lines. I do not know which files will come in as the input. If the files have these lines they will be removed.

I have a different problem. In this filter file, I want to add code for removing lines between two specific tags. For example, if the file has

MYTAG1
line1
line2
line3
MYTAG2
line1
line2

I want to remove all line from MYTAG1 up untill MYTAG2 but not MYTAG2. So the file should look like after filtering: MYTAG2
Line1
line2

What I have currently is the following code:

<CODE>if (/^MYTAG1/ .. /^MYTAG2/){
return 0;
}

But this would remove the MYTAG2 line from the file. I do not want to remove the MYTAG2.

Would using "last" help? How to use it?

Please help!

A Learning Monk!

Replies are listed 'Best First'.
•Re: How do I remove lines from a file...
by merlyn (Sage) on Apr 09, 2002 at 23:14 UTC
    The value returned from the scalar dot-dot operator is the line-number count of the hit, with "E0" appended on the closing line. So, just check for that:
    while (<>) { print unless $count = /^MYTAG1/ .. /^MYTAG2/ and not $count =~ /E0/; }

    -- Randal L. Schwartz, Perl hacker

Re: How do I remove lines from a file...
by thelenm (Vicar) on Apr 09, 2002 at 21:31 UTC
    Here's how I would do it. There's probably a better way though :-) I'm not sure how to modify my code to use return 0, but here it is:
    my $removing = 0; while (<>) { if (/^MYTAG1/) { $removing = 1; } elsif (/^MYTAG2/) { $removing = 0; } print unless $removing; }
Fish
by Fletch (Bishop) on Apr 09, 2002 at 21:23 UTC
    while( <> ) { do { print; last } if /^MYTAG2/; } print while <>;
      hm. you have to consider that with your code every line from the beginning of the file until /^MYTAG2/ will be skipped, instead of the text between /^MYTAG1/ and /^MYTAG2/

        Correct, but given the example data file it works. :)

        If the file doesn't start with MYTAG1, then you'd of course need to prefix with

        while( <> ) { last if /^MYTAG1/; print }

        Or use something like Re: How do I remove lines from a file....