rich.wilder has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,

I'm trying to eliminate some extraneous text from lines from a list file. The lines are read into $_ and I want to change a line like so:

clrf __pbssCOMRAM& (0+255),c

to:

clrf __pbssCOMRAM,c

So I need to substitute the string '& (0+255)' with ''.

I've tried:

s/& (0+255)//; s/'& (0+255)'//; s/"& (0+255)"//; s/q(& (0+255))//;

All with the same end result: no substitution takes place. Other simpler substitutions work like:

s/,/, /;

gives the expected result

clrf __pbssCOMRAM& (0+255), c

Please help!

Richard

Replies are listed 'Best First'.
Re: Arguments to substitution question
by davido (Cardinal) on Sep 12, 2015 at 03:24 UTC

    You are failing to escape the parenthesis, so they are carrying their structural meaning rather than being treated as plain old anchor text in the pattern. Simalarly the + is a quantifier; it carries meaning as well. Try this:

    s/& \(0\+255\)//;

    Here's an example:

    my $have = q{clrf __pbssCOMRAM& (0+255),c}; my $want = q{clrf __pbssCOMRAM,c}; $have =~ s/& \(0\+255\)//; print "$have\n$want\n"; print "They ", ($have eq $want ? '' : "don't "), "match\n";

    If you want to figure out how to use regular expressions with Perl, perlretut and perlrequick are good starting points.

    Another strategy is to tell Perl that what follows should have any "special characters" escaped automatically:

    s/\Q& (0+255)//;

    The \Q feature is documented in quotemeta.


    Dave

      Dave,

      That worked!

      Thanks!,

      Richard

        $_ = "clrf__pbssCOMRAM&(0+255),c"; s/(.*\&).*(\,c)/$1$2/; print $_;

        ofcourse i saw this ques answered but may be you can use code this way too :p