in reply to Replace character not inside comments

Japhy can probably tell you how to do it in one go, with much looking about, but I'll have to settle for three lines: first remove and store comments, then strip the backslashes, then restore the comments. This seems to work:

my $test = q|\AFZ\BJK \*\AFZ...*\ |; my @comments; $test =~ s/(\\\*.*?\*\\)/ push @comments, $1; '%%comment%%' /eg; $test =~ s/\\//g; $test =~ s/%%comment%%/ shift @comments /eg; print $test;

Any old marker will do as long as it doesn't appear in your text: something long and random would probably be best. %%comment%% was just the first thing that came into my head.

ps. goes clunk, i know, but easy to follow

Replies are listed 'Best First'.
Re: Re: Replace character not inside comments
by Anonymous Monk on Sep 04, 2002 at 19:44 UTC
    how would i make this work if the comment spanned more than 1 line?

      just adding an s modifier to each regex ought to do it: it'll then treat the whole thing as if it were one line (or, strictly, it'll treat line-endings as just another character), as the early parts of perlre will explain. I should have put that in, but your example was just one line so I didn't bother:

      $test =~ s/(\\\*.*?\*\\)/ push @comments, $1; '%%comment%%' /egs; $test =~ s/\\//gs; $test =~ s/%%comment%%/ shift @comments /egs;