There is nothing special about a character sequence that includes \ . If you want to replace one sequence of characters with another, this is very easy to do in Perl:
my %sequences = ( '\\t' => "\t", '\\n' => "\n", 'foo' => 'bar', ); my $string = '\\tstring fool string\\tfoo\\n'; print "Before: [$string]\n"; $string =~ s/\Q$_/$sequences{$_}/g for ( keys %sequences ); print "After: [$string]\n";
The only trick with \ is to keep track of when Perl considers it an escape character.
Before: [\tstring fool string\tfoo\n] After: [ string barl string bar ]
However, as darch notes , you can just use String :: Escape .
Note that you must be very careful when accepting values โโfrom environment variables. I would not want to use String::Escape , since it could handle a little more than you are ready to translate. The safe way is to only expand on the specific values โโthat you explicitly want to allow. See the โSafe Programming Techniquesโ chapter in Mastering Perl for a discussion of this, along with a taint test that you might want to use in this case.
source share