在Perl中,假设我有一个字符串'hello\tworld\n'
,我想要的是:
'hello world
'
也就是说,字符串应该是 "hello",然后是一个制表符,然后是 "world",然后是一个换行符。或者等价于
"hello\tworld\n"
(注意双引号)。换句话说,是否有一个函数可以接受具有转义序列的字符串,并返回一个等效的字符串,其中所有转义序列都被插值?我不想插值变量或其他任何东西,只想插值转义序列,比如
\x
,其中 x
是一个字母。在Perl中,假设我有一个字符串'hello\tworld\n'
,我想要的是:
'hello world
'
"hello\tworld\n"
(注意双引号)。\x
,其中 x
是一个字母。use String::Escape qw(unbackslash);
my $s = unbackslash('hello\tworld\n');
my $string = 'hello\tworld\n';
my $decoded_string = eval "\"$string\"";
my $string = 'hello\tworld\n';
$string =~ s#([^\\A-Za-z_0-9])#\\$1#gs;
my $decoded_string = eval "\"$string\"";
这段代码几乎和quotemeta函数相同,但是它免除了对'\'字符的转义。
编辑2:尽管如此,这仍然不是100%安全的,因为如果最后一个字符是'\',它将会“泄漏”到字符串末尾之外...
个人而言,如果我想要100%的安全性,我会使用特定替换的哈希表,并使用正则表达式替换而非eval函数:
my %sub_strings = (
'\n' => "\n",
'\t' => "\t",
'\r' => "\r",
);
$string =~ s/(\\n|\\t|\\n)/$sub_strings{$1}/gs;
eval
和quotemeta
的组合来实现这个吗?基本上,(my $interpolated_string = eval(q(") . quotemeta($string) . q("))) =~ s/\\(.)/\1/g
。 - Ryan C. Thompson\x
,其中x
是任何字母。不包括变量或其他东西。 - Ryan C. Thompson