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

I'm writing a find/replace script, and am running into issues with the ampersand and pound signs.

q[<IL.Check/>]=>q[<&#x221a;>],

In the previous example, I'm trying to find <IL.Check/> and replace it with &#x221a;. I have even added quotes, as in "&#x221a;" or &"#"x221a;, but in both cases the quotes appear in the output.

Am I adding quotes in the wrong place, or do I also need to add something for the ampersand?

Any help is appreciated, thanks.

Replies are listed 'Best First'.
Re: How to ignore ampersand and pound signs?
by bichonfrise74 (Vicar) on Nov 04, 2009 at 01:25 UTC
    Hmm... not sure if I understood your question, but hopefully this would help you out.
    #!/usr/bin/perl use strict; my $a = qq{<IL.Check/>}; my $b = qq{<&#x221a;>}; print "Old word: $a\n"; $a =~ s/$a/$b/; print "New word: $a\n";

      Thank you!

      The double q (qq) worked!

      Sorry for the basic question, I'm just starting out with Perl. :-)

        Nonsense. The single quote you originally posted works just as well.
        my $s = q[<IL.Check/>]; my $r = q[<&#x221a;>]; print "Old word: $s\n"; $s =~ s/$s/$r/; print "New word: $s\n";

        There's no interpolation or escape sequences here. q vs qq is moot.

        The real problem is that you are using text as a regex pattern without first converting it to a regex pattern. ("#" is special under "x".) Use quotemeta or its alias \Q..\E:

        my $s = q[<IL.Check/>]; my $r = q[<&#x221a;>]; print "Old word: $s\n"; $s =~ s/\Q$s\E/$r/; print "New word: $s\n";