Kir*_*rby 1 perl printf arguments
需要构建一个字符串foobar is not foo and not bar.
在printf格式中%$2s,"2"表示特定的参数位置.
但它在perl中不起作用:
$ perl -e "printf('%$1s$2s is not %$1s and not %$2s', 'foo', 'bar');"
%2 is not %1 and not %2
Run Code Online (Sandbox Code Playgroud)
我的环境:
$ perl --version
This is perl 5, version 16, subversion 3 (v5.16.3) built for x86_64-linux-thread-multi
(with 29 registered patches, see perl -V for more detail)
Run Code Online (Sandbox Code Playgroud)
你的报价是关闭的.
perl -E 'say sprintf(q{%1$s%2$s is not %1$s and not %2$s}, "foo", "bar");'
foobar is not foo and not bar
Run Code Online (Sandbox Code Playgroud)
你不能使用双引号"",-e因为你的shell会混淆.你需要单引号.但是如果你使用printf带%1$s语法的模式使用双引号,Perl将尝试插入$s,这不起作用.因此,使用非引用q{}或逃避单引号''与\'.或逃避$s.
如果你打开use strict,use warnings你会看到:
$ perl -E 'use strict; use warnings; say sprintf("%1$s%2$s is not %1$s and not %2$s", "foo", "bar");'
Global symbol "$s" requires explicit package name at -e line 1.
Global symbol "$s" requires explicit package name at -e line 1.
Global symbol "$s" requires explicit package name at -e line 1.
Global symbol "$s" requires explicit package name at -e line 1.
Execution of -e aborted due to compilation errors.
Run Code Online (Sandbox Code Playgroud)
这是用单引号''的-e双引号""的模式.
$ perl -E "use strict; use warnings; say sprintf('%1$s%2$s is not %1$s and not %2$s', 'foo', 'bar');"
Invalid conversion in sprintf: "%1 " at -e line 1.
Invalid conversion in sprintf: "%2" at -e line 1.
%2 is not %1 and not %2
Run Code Online (Sandbox Code Playgroud)
现在shell试图$s通过双引号进行插值"".所以Perl从未见过它.它将模式视为"%1 %2 is not %1 and not %2"无法理解的模式.(注意,%不会在Perl中的双引号字符串中插入).
| 归档时间: |
|
| 查看次数: |
151 次 |
| 最近记录: |