# Perl 標準関数: sprintf ## sprintf sprintf FORMAT, LIST Returns a string formatted by the usual `printf` conventions of the C library function `sprintf`. See below for more details and see sprintf(3) or printf(3) on your system for an explanation of the general principles. For example: # Format number with up to 8 leading zeroes $result = sprintf("%08d", $number); # Round number to 3 digits after decimal point $rounded = sprintf("%.3f", $number); Perl does its own `sprintf` formatting--it emulates the C function `sprintf`, but it doesn't use it (except for floating-point numbers, and even then only the standard modifiers are allowed). As a result, any non-standard extensions in your local `sprintf` are not available from Perl. Unlike `printf`, `sprintf` does not do what you probably mean when you pass it an array as your first argument. The array is given scalar con-text, and instead of using the 0th element of the array as the format, Perl will use the count of elements in the array as the format, which is almost never useful. Perl の *sprintf* は Cライブラリの sprintf 相当のフォーマットを行った文字列を返します。 詳しくは sprintf(3) もしくは printf(3) を参照してください。 * perl の sprintf は自前実装 * C の sprintf エミュレート * sprintf の第一引数はスカラコンテキスト * リストを渡しても 0 番目の要素ではなく、配列の要素数が渡ってしまう ## フォーマット指定文字 ------------ | ----------- | | **%%** | % | | **%c** | 渡された文字コードによる文字 | | **%s** | 文字列 | | **%d** | 整数: 10進数 | | **%u** | 符号無し整数: 10進数 | | **%o** | 符号無し整数: 8進数 | | **%b** | 符号無し整数: 2進数 | | **%x**, **%X** | 符号無し整数: 16進数 (%X は大文字バージョン) | | **%e**, **%E** | 浮動小数点数: 指数表示 (%E は大文字バージョン) *表記はシステム依存| | **%f** | 浮動小数点数: 10進数表示 | | **%g**, **%G** | 浮動小数点数 %e or %f: (%G は、適用できる場合 %E 相当) *表記はシステム依存 | 例: print sprintf("%c", 88); # X print sprintf("%s", 'bar'); # bar print sprintf("%5s", 'bar'); # ' bar' print sprintf("%-5s", 'bar'); # 'bar ' print sprintf("%d", 12345.6789); # 12345 print sprintf("%06d", 12345.6789); # 012345 print sprintf("%.2f", 12345.6789); # 12345.68 print sprintf("%.*f", 3, 12345.6789); # 12345.678 ------------ | ----------- | | **%p** | a pointer (outputs the Perl value's address in hexadecimal) | | **%n** | special: stores the number of characters output so far into the next variable in the parameter list | ## See Also perldoc -f sprintf