2016-11-07 14 views
1

需要建立一個字符串foobar is not foo and not bar在命令行中,是否可以在perl中以printf格式獲取特定參數?

printf格式%$2s,「2」表示特定的參數位置。

不過,這並不在Perl的工作:

$ perl -e "printf('%$1s$2s is not %$1s and not %$2s', 'foo', 'bar');" 
%2 is not %1 and not %2 

我ENV:

$ 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) 
+0

@HunterMcMillen,你的意思是創建一個函數? ''perl -e'sub ppp(){printf('%1 $ s%2 $ s不是%1 $ s而不是%2 $ s','foo','bar');} ppp();「 「像這樣?這不起作用。 – Kirby

回答

6

您的報價已關閉。

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 

,因爲你的shell會很困惑,你不能使用的-e雙引號""。你需要單引號。但是如果使用printf模式的雙引號和%1$s語法,Perl會嘗試插入$s,這不起作用。因此請使用非引用的q{}或使用\'轉義單引號''。或者逃脫$ s。

如果打開use strictuse 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. 

與單引號''-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 

現在殼試圖插$s因爲雙引號""的。所以Perl永遠不會看到它。它認爲該模式爲"%1 %2 is not %1 and not %2",它無法理解。 (請注意,%不會在Perl中用雙引號字符串插入)。

+0

我明白了這一點,謝謝!有點不清楚,如果我使用單引號,爲什麼會導致錯誤:'perl -E'使用strict;使用警告;說sprintf(\'%1 $ s%2 $ s不是%1 $ s而不是%2 $ s \',\'foo \',\'bar \');''。錯誤:'bash:語法錯誤附近的意外令牌')'' – Kirby

+1

@Kirby這是一個很好的問題。如果刪除括號'('和')'(你不需要它們),它只會需要更多的輸入而不能運行你的程序。離開我的頭頂,我不知道它不喜歡什麼。但shell引用和轉義是棘手的。我的建議是使用'q {}'作爲模式,以及任何你喜歡的參數。我會'printf q {%1 $ d ...},qw(foo bar);'所以我根本不用處理引號 – simbabque

+0

明白了,謝謝! – Kirby

2

這對我的作品在* nix:

perl -e "printf('%s%s is not %1\$s and not %2\$s', 'foo', 'bar');" 

sprintf documentation,在特別是最後的例子:

Here are some more examples; be aware that when using an explicit index, the $ may need escaping:

printf "%2\$d %d\n",  12, 34;  # will print "34 12\n" 
printf "%2\$d %d %d\n", 12, 34;  # will print "34 12 34\n" 
printf "%3\$d %d %d\n", 12, 34, 56; # will print "56 12 34\n" 
printf "%2\$*3\$d %d\n", 12, 34, 3; # will print " 34 12\n" 
printf "%*1\$.*f\n",  4, 5, 10; # will print "5.0000\n" 
1

讓我們來看看該程序傳遞給perl

$ printf '%s' "printf('%$1s$2s is not %$1s and not %$2s', 'foo', 'bar');" 
printf('%ss is not %s and not %s', 'foo', 'bar'); 

正如你所看到的,有在你的程序中沒有$1$2,因爲你不正確建立你的shell命令。就像Perl插入雙引號一樣,sh和相關的shell也是如此。你應該使用單引號!

perl -e'printf("%\$1s\$2s is not %\$1s and not %\$2s\n", "foo", "bar");' 

(我會建議從''切換到q{} Perl程序裏面,所以你不會有逃離的美元符號,但你需要雙引號的\n你反正失蹤。)

相關問題