为什么我不能将sprintf的变量字符串传递给perl脚本



我遇到了以下perl问题。将这段代码放入test.pl

my $str=shift;
printf "$str", @ARGV;

然后像这样运行:

perl test.pl "xtx%sn%s" one two three

我的预期输出应该是:

x    xone
two

相反,我得到了

xsxonentwo

我哪里错了?

Perl在编译时转换字符串中的转义序列,因此一旦程序运行,就太晚了,无法将"t""n"转换为制表符和换行符。

使用eval可以解决这个问题,但它非常不安全。我建议您在编译后使用String::Interpolate模块来处理字符串。它使用Perl的原生插值引擎,因此具有与将字符串编码到程序中完全相同的效果。

你的test.pl变成

use strict;
use warnings;
use String::Interpolate qw/ interpolate /;
my $str = shift;
printf interpolate($str), @ARGV;

输出

E:Perlsource>perl test.pl "xtx%sn%s" one two three
x       xone
two
E:Perlsource>

更新

如果你只想允许String::Interpolate支持的可能性的一小部分,那么你可以写一些明确的东西,比如

use strict;
use warnings;
my $str = shift;
$str =~ s/\t/t/g;
$str =~ s/\n/n/g;
printf $str, @ARGV;

但模块或CCD_ 7是在命令行上支持通用Perl字符串的唯一真正方法。

最新更新