我遇到了以下 perl 问题。把这段代码放到test.pl中
my $str=shift;
printf "$str", @ARGV;
然后像这样运行它:
perl test.pl "x\tx%s\n%s" one two three
我的预期输出应该是:
x xone
two
我得到了
x\sxone\ntwo
我哪里错了?
最佳答案
Perl 在编译时转换字符串中的转义序列,因此一旦您的程序运行,您就太迟无法将 "\t"
和 "\n"
转换为制表符和换行符。
使用 eval
可以解决这个问题,但它非常不安全。我建议您使用 String::Interpolate
编译后处理字符串的模块。它使用 Perl 的 native 插值引擎,因此效果与将字符串编码到程序中完全相同。
你的 test.pl
变成了
use strict;
use warnings;
use String::Interpolate qw/ interpolate /;
my $str = shift;
printf interpolate($str), @ARGV;
输出
E:\Perl\source>perl test.pl "x\tx%s\n%s" one two three
x xone
two
E:\Perl\source>
更新
如果您只想允许 String::Interpolate
支持的一小部分可能性,那么您可以写一些明确的东西,比如
use strict;
use warnings;
my $str = shift;
$str =~ s/\\t/\t/g;
$str =~ s/\\n/\n/g;
printf $str, @ARGV;
但模块或 eval
是在命令行上支持通用 Perl 字符串的唯一真正方法。
关于perl - 为什么我不能将 sprintf 的变量字符串传递给 perl 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17676947/