in reply to delete above matching line?

Your while-loop reads line by line, so you can never match the previous line in a regex.

I gets much easier if you read the whole file into a string, and then apply a substitution.

I don't know what output you expect, but this might do you want:

s/^\s*start_of_block\s*\{.*?\};\s*//xmsg;

If not, please tell us exactly what output you want.

Perl 6 - links to (nearly) everything that is Perl 6.

Replies are listed 'Best First'.
Re^2: delete above matching line?
by oldmanwillow (Novice) on Jul 01, 2010 at 07:56 UTC

    Reading the file into a string did the trick, thanks.

    { local $/ = undef ; open TEST,'test' or die "Denied: $!\n" ; my $string = <TEST> ; close TEST ; $string =~ s/\n\nstart_of_block.*?};//s ; print $string ; }
      For bigger files:
      my @out; my $print = 1; while (<>) { if (m/^start_of_block/) { $print = 0; pop @out if @out and $out[-1] eq $/; # removes previous empty line } push @out, $_ if $print; if (m/^};/) { $print = 1; } print shift @out if $print and 1 < @out; } # UPDATE: based on oldmanwillow reply: # print @out; print @out if $out[-1] =~ /^\s*$/ ;

        This almost works, and I like it much better than reading the whole file into a string. Thanks!

        The only problem is that as it is, the script leaves a trailing newline if the deleted block is the last in the file. Probably my fault for not specifying that the blocks run to the end of the file.

        The fix is simply to change the last

        print @out ;

        to

        print @out if $out[-1] =~ /^\s*$/ ;