Humanity

Edit the world by your favorite way

boost::formatみたいな指定ができるPerlのsprintf()

元記事はこちら。 *1

% perl -E'say sprintf(q[%d %d %d], 1, 2, 3)'
1 2 3

% perl -E'say sprintf(q[%2$d %3$d %1$d], 1, 2, 3)'
2 3 1

http://id-perl.blogspot.com/2010/04/tip-sprintf.html

「%2$d」のように指定すると2引数目が取れるんですね。文字列なら「%2$s」。


ちなみにPythonではこんな風にもできるらしい。

print 'This {food} is {adjective}.'.format(adjective='absolutely horrible', food='spam') # => This spam is absolutely horrible.

http://id-perl.blogspot.com/2010/04/tip-sprintf.html

これはいいなーと思っていたらそれString::Formatterでできるそうで

# $extra = {mverb => "harus"}; # mverb juga bisa 'sebaiknya'
# $args = [1, 10];
print stringf("Data %(mverb)s di antara %(0)d sampai %(1)d", $args, $extra); # => Data harus lebih kecil di antara 1 sampai 10.

http://id-perl.blogspot.com/2010/04/tip-sprintf.html

こんな風に書けるらしい。
他にもuse時にいろいろ引数を渡して挙動を変えるなどできるらしい。*2
詳しくはperldocで。

*1:インドネシア語らしい

*2:これってどうなんだろう。個人的には別の関数かオプション引数で挙動を変えた方が柔軟性ある気がするけど