by sram · 16y ago · 0 comments
#!/usr/bin/perl
$in = <STDIN>;
$remove = <STDIN>;
chomp ($remove);
chomp ($in);
$in =~ s/$remove//g;
>hello|goodbye
>|
>>Result is 'hello|goodbye'
>That's a nice dog you have there.
>.
>>Result is ''
I usually handle this with: my $pattern = '\\'.substr($in,0,1);
$in =~ s/$pattern//g;
but it still doesn't feel safe. String operations in perl usually do what you want, but be careful with them! $in =~ s/\Q$remove\E//g;
man perlre, search for \Q. When \Q and \E'ing a variable like that, a literal "\E" in the variable value can not escape from the outer \Q. perl -pe'BEGIN { $x = quotemeta(shift) } s/$x//g;'
should do what you want. `quotemeta' is the function that does the escaping for your properly.I was hoping to be able to use tr///, since it seems like it was built for this, but it creates its conversion tables at compile time, so there's no chance to interpolate the argument without some nasty nasty eval'ing.