Pergunta

I have a Perl string with special characters and newlines which needs to be passed to a command line utility (which does not accept special chars unless escaped).

How do I substitute each special character with preceding \?

I could substitute each char separately, but want to know whether there is a better way?

String comes as follows when read from a cell in a spreasheet.

<meta property="og:url" content="http://www.example.com/test/testpage.aspx?ID=OO3JUPVSWjs%3d&ContentTypeId=qbeAILfmBIE%3d" />

I tried $str =~ /^\Q$str\E/;

but that fails when the variable is passed to the command line utility.

Foi útil?

Solução

As you've already pointed out, you can just use quotemeta

$str = quotemeta $str;

However, if that isn't good for whatever reason, you can just build your own character class of characters that you want to escape

$str =~ s/([\\'"])/\\$1/g;

Outras dicas

You can build the pattern and perform the match separately:

my $pattern = "$bar";
my $regex = "\Q$pattern\E";

if ( q(foo $bar baz) =~ /$regex/ ) {
    print "match\n"
}
else {
    print "no match\n"
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top