perl-5.38.0
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.

C ライブラリ関数 sprintf の 普通の printf 記法の 整形された文字列を返します。 一般的な原則の説明については以下の説明と、システムの sprintf(3) または printf(3) の説明を参照してください。

For example:

例えば:

        # Format number with up to 8 leading zeroes
        my $result = sprintf("%08d", $number);

        # Round number to 3 digits after decimal point
        my $rounded = sprintf("%.3f", $number);

Perl does its own sprintf formatting: it emulates the C function sprintf(3), but doesn't use it except for floating-point numbers, and even then only standard modifiers are allowed. Non-standard extensions in your local sprintf(3) are therefore unavailable from Perl.

Perl は sprintf フォーマット処理を自力で行います: これは C の sprintf(3) 関数をエミュレートしますが、C の関数は使いません (浮動小数点を除きますが、それでも標準の記述子のみが利用できます)。 従って、ローカルな非標準の sprintf(3) 拡張機能は 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 context, 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.

printf と違って、 sprintf の最初の引数に配列を渡しても あなたが多分望むとおりには動作しません。 配列はスカラコンテキストで渡されるので、配列の 0 番目の要素ではなく、 配列の要素数をフォーマットとして扱います; これはほとんど役に立ちません。

Perl's sprintf permits the following universally-known conversions:

Perl の sprintf は以下の一般に知られている変換に 対応しています:

   %%    a percent sign
   %c    a character with the given number
   %s    a string
   %d    a signed integer, in decimal
   %u    an unsigned integer, in decimal
   %o    an unsigned integer, in octal
   %x    an unsigned integer, in hexadecimal
   %e    a floating-point number, in scientific notation
   %f    a floating-point number, in fixed decimal notation
   %g    a floating-point number, in %e or %f notation
   %%    パーセントマーク
   %c    与えられた番号の文字
   %s    文字列
   %d    符号付き 10 進数
   %u    符号なし 10 進数
   %o    符号なし 8 進数
   %x    符号なし 16 進数
   %e    科学的表記の浮動小数点数
   %f    固定 10 進数表記の浮動小数点数
   %g    %e か %f の表記の浮動小数点数

In addition, Perl permits the following widely-supported conversions:

さらに、Perl では以下のよく使われている変換に対応しています:

   %X    like %x, but using upper-case letters
   %E    like %e, but using an upper-case "E"
   %G    like %g, but with an upper-case "E" (if applicable)
   %b    an unsigned integer, in binary
   %B    like %b, but using an upper-case "B" with the # flag
   %p    a pointer (outputs the Perl value's address in hexadecimal)
   %n    special: *stores* the number of characters output so far
         into the next argument in the parameter list
   %a    hexadecimal floating point
   %A    like %a, but using upper-case letters
   %X    %x と同様だが大文字を使う
   %E    %e と同様だが大文字の "E" を使う
   %G    %g と同様だが(適切なら)大文字の "E" を使う
   %b    符号なし 2 進数
   %B    %b と同様だが、# フラグで大文字の "B" を使う
   %p    ポインタ (Perl の値のアドレスを 16 進数で出力する)
   %n    特殊: 出力文字数を引数リストの次の変数に「格納」する
   %a    16 進浮動小数点
   %A    %a と同様だが、大文字を使う

Finally, for backward (and we do mean "backward") compatibility, Perl permits these unnecessary but widely-supported conversions:

最後に、過去との互換性(これは「過去」だと考えています)のために、 Perl は以下の不要ではあるけれども広く使われている変換に対応しています。

   %i    a synonym for %d
   %D    a synonym for %ld
   %U    a synonym for %lu
   %O    a synonym for %lo
   %F    a synonym for %f
   %i    %d の同義語
   %D    %ld の同義語
   %U    %lu の同義語
   %O    %lo の同義語
   %F    %f の同義語

Note that the number of exponent digits in the scientific notation produced by %e, %E, %g and %G for numbers with the modulus of the exponent less than 100 is system-dependent: it may be three or less (zero-padded as necessary). In other words, 1.23 times ten to the 99th may be either "1.23e99" or "1.23e099". Similarly for %a and %A: the exponent or the hexadecimal digits may float: especially the "long doubles" Perl configuration option may cause surprises.

%e, %E, %g, %G において、指数部が 100 未満の場合の 指数部の科学的な表記法はシステム依存であることに注意してください: 3 桁かもしれませんし、それ以下かもしれません(必要に応じて 0 で パッディングされます)。 言い換えると、 1.23 掛ける 10 の 99 乗は "1.23e99" かもしれませんし "1.23e099" かもしれません。 同様に %a%A の場合: 指数部と 16 進数が浮動小数点かもしれません: 特に "long doubles" Perl 設定オプションが驚きを引き起こすかもしれません。

Between the % and the format letter, you may specify several additional attributes controlling the interpretation of the format. In order, these are:

% とフォーマット文字の間に、フォーマットの解釈を制御するための、 いくつかの追加の属性を指定できます。 順番に、以下のものがあります:

format parameter index

(フォーマットパラメータインデックス)

An explicit format parameter index, such as 2$. By default sprintf will format the next unused argument in the list, but this allows you to take the arguments out of order:

2$ のような明示的なフォーマットパラメータインデックス。 デフォルトでは sprintf はリストの次の使われていない引数を フォーマットしますが、これによって異なった順番の引数を使えるようにします:

  printf '%2$d %1$d', 12, 34;      # prints "34 12"
  printf '%3$d %d %1$d', 1, 2, 3;  # prints "3 1 1"
flags

(フラグ)

one or more of:

以下のうちの一つまたは複数指定できます:

   space   prefix non-negative number with a space
   +       prefix non-negative number with a plus sign
   -       left-justify within the field
   0       use zeros, not spaces, to right-justify
   #       ensure the leading "0" for any octal,
           prefix non-zero hexadecimal with "0x" or "0X",
           prefix non-zero binary with "0b" or "0B"
   space   非負数の前に空白をつける
   +       非負数の前にプラス記号をつける
   -       フィールド内で左詰めする
   0       右詰めに空白ではなくゼロを使う
   #       8 進数では確実に先頭に "0" をつける;
           非 0 の 16 進数では "0x" か "0X" をつける;
           非 0 の 2 進数では "0b" か "0B" をつける

For example:

例えば:

  printf '<% d>',  12;   # prints "< 12>"
  printf '<% d>',   0;   # prints "< 0>"
  printf '<% d>', -12;   # prints "<-12>"
  printf '<%+d>',  12;   # prints "<+12>"
  printf '<%+d>',   0;   # prints "<+0>"
  printf '<%+d>', -12;   # prints "<-12>"
  printf '<%6s>',  12;   # prints "<    12>"
  printf '<%-6s>', 12;   # prints "<12    >"
  printf '<%06s>', 12;   # prints "<000012>"
  printf '<%#o>',  12;   # prints "<014>"
  printf '<%#x>',  12;   # prints "<0xc>"
  printf '<%#X>',  12;   # prints "<0XC>"
  printf '<%#b>',  12;   # prints "<0b1100>"
  printf '<%#B>',  12;   # prints "<0B1100>"

When a space and a plus sign are given as the flags at once, the space is ignored.

空白とプラス記号がフラグとして同時に与えられると、 空白は無視されます。

  printf '<%+ d>', 12;   # prints "<+12>"
  printf '<% +d>', 12;   # prints "<+12>"

When the # flag and a precision are given in the %o conversion, the precision is incremented if it's necessary for the leading "0".

%o 変換に # フラグと精度が与えられると、先頭の "0" が必要な場合は 精度に 1 が加えられます。

  printf '<%#.5o>', 012;      # prints "<00012>"
  printf '<%#.5o>', 012345;   # prints "<012345>"
  printf '<%#.0o>', 0;        # prints "<0>"
vector flag

(ベクタフラグ)

This flag tells Perl to interpret the supplied string as a vector of integers, one for each character in the string. Perl applies the format to each integer in turn, then joins the resulting strings with a separator (a dot . by default). This can be useful for displaying ordinal values of characters in arbitrary strings:

このフラグは Perl に、与えられた文字列を、文字毎に一つの整数のベクタとして 解釈させます。 Perl は各数値をフォーマットし、それから結果の文字列をセパレータ (デフォルトでは .)で連結します。 これは任意の文字列の文字を順序付きの値として表示するのに便利です:

  printf "%vd", "AB\x{100}";           # prints "65.66.256"
  printf "version is v%vd\n", $^V;     # Perl's version

Put an asterisk * before the v to override the string to use to separate the numbers:

アスタリスク *v の前に置くと、数値を分けるために使われる文字列を 上書きします:

  printf "address is %*vX\n", ":", $addr;   # IPv6 address
  printf "bits are %0*v8b\n", " ", $bits;   # random bitstring

You can also explicitly specify the argument number to use for the join string using something like *2$v; for example:

また、*2$v のように、連結する文字列として使う引数の番号を明示的に 指定できます; 例えば:

  printf '%*4$vX %*4$vX %*4$vX',       # 3 IPv6 addresses
          @addr[1..3], ":";
(minimum) width

((最小)幅)

Arguments are usually formatted to be only as wide as required to display the given value. You can override the width by putting a number here, or get the width from the next argument (with *) or from a specified argument (e.g., with *2$):

引数は、普通は値を表示するのに必要なちょうどの幅でフォーマットされます。 ここに数値を置くか、(* で)次の引数か(*2$ で)明示的に指定した引数で 幅を上書きできます。

 printf "<%s>", "a";       # prints "<a>"
 printf "<%6s>", "a";      # prints "<     a>"
 printf "<%*s>", 6, "a";   # prints "<     a>"
 printf '<%*2$s>', "a", 6; # prints "<     a>"
 printf "<%2s>", "long";   # prints "<long>" (does not truncate)

If a field width obtained through * is negative, it has the same effect as the - flag: left-justification.

* を通して得られたフィールドの値が負数の場合、- フラグと 同様の効果 (左詰め) があります。

precision, or maximum width

(精度あるいは最大幅)

You can specify a precision (for numeric conversions) or a maximum width (for string conversions) by specifying a . followed by a number. For floating-point formats except g and G, this specifies how many places right of the decimal point to show (the default being 6). For example:

. の後に数値を指定することで、(数値変換の場合)精度や(文字列変換の場合) 最大幅を指定できます。 小数点数フォーマットの場合、gG を除いて、表示する小数点以下の 桁数を指定します(デフォルトは 6 です)。 例えば:

  # these examples are subject to system-specific variation
  printf '<%f>', 1;    # prints "<1.000000>"
  printf '<%.1f>', 1;  # prints "<1.0>"
  printf '<%.0f>', 1;  # prints "<1>"
  printf '<%e>', 10;   # prints "<1.000000e+01>"
  printf '<%.1e>', 10; # prints "<1.0e+01>"

For "g" and "G", this specifies the maximum number of significant digits to show; for example:

"g" と "G" の場合、これは最大有効数字を指定します; 例えば:

  # These examples are subject to system-specific variation.
  printf '<%g>', 1;        # prints "<1>"
  printf '<%.10g>', 1;     # prints "<1>"
  printf '<%g>', 100;      # prints "<100>"
  printf '<%.1g>', 100;    # prints "<1e+02>"
  printf '<%.2g>', 100.01; # prints "<1e+02>"
  printf '<%.5g>', 100.01; # prints "<100.01>"
  printf '<%.4g>', 100.01; # prints "<100>"
  printf '<%.1g>', 0.0111; # prints "<0.01>"
  printf '<%.2g>', 0.0111; # prints "<0.011>"
  printf '<%.3g>', 0.0111; # prints "<0.0111>"

For integer conversions, specifying a precision implies that the output of the number itself should be zero-padded to this width, where the 0 flag is ignored:

整数変換の場合、精度を指定すると、数値自体の出力はこの幅に 0 で パッディングするべきであることを暗に示すことになり、0 フラグは 無視されます:

  printf '<%.6d>', 1;      # prints "<000001>"
  printf '<%+.6d>', 1;     # prints "<+000001>"
  printf '<%-10.6d>', 1;   # prints "<000001    >"
  printf '<%10.6d>', 1;    # prints "<    000001>"
  printf '<%010.6d>', 1;   # prints "<    000001>"
  printf '<%+10.6d>', 1;   # prints "<   +000001>"

  printf '<%.6x>', 1;      # prints "<000001>"
  printf '<%#.6x>', 1;     # prints "<0x000001>"
  printf '<%-10.6x>', 1;   # prints "<000001    >"
  printf '<%10.6x>', 1;    # prints "<    000001>"
  printf '<%010.6x>', 1;   # prints "<    000001>"
  printf '<%#10.6x>', 1;   # prints "<  0x000001>"

For string conversions, specifying a precision truncates the string to fit the specified width:

文字列変換の場合、精度を指定すると、指定された幅に収まるように文字列を 切り詰めます:

  printf '<%.5s>', "truncated";   # prints "<trunc>"
  printf '<%10.5s>', "truncated"; # prints "<     trunc>"

You can also get the precision from the next argument using .*, or from a specified argument (e.g., with .*2$):

.* を使って精度を次の引数から取ったり、 (.*2$ のように) 指定した引数から取ったりすることもできます:

  printf '<%.6x>', 1;       # prints "<000001>"
  printf '<%.*x>', 6, 1;    # prints "<000001>"

  printf '<%.*2$x>', 1, 6;  # prints "<000001>"

  printf '<%6.*2$x>', 1, 4; # prints "<  0001>"

If a precision obtained through * is negative, it counts as having no precision at all.

* によって得られた精度が負数の場合、精度が指定されなかった場合と 同じ効果となります。

  printf '<%.*s>',  7, "string";   # prints "<string>"
  printf '<%.*s>',  3, "string";   # prints "<str>"
  printf '<%.*s>',  0, "string";   # prints "<>"
  printf '<%.*s>', -1, "string";   # prints "<string>"

  printf '<%.*d>',  1, 0;   # prints "<0>"
  printf '<%.*d>',  0, 0;   # prints "<>"
  printf '<%.*d>', -1, 0;   # prints "<0>"
size

(サイズ)

For numeric conversions, you can specify the size to interpret the number as using l, h, V, q, L, or ll. For integer conversions (d u o x X b i D U O), numbers are usually assumed to be whatever the default integer size is on your platform (usually 32 or 64 bits), but you can override this to use instead one of the standard C types, as supported by the compiler used to build Perl:

数値変換では、l, h, V, q, L, ll を使って解釈する数値の 大きさを指定できます。 整数変換 (d u o x X b i D U O) では、数値は通常プラットフォームの デフォルトの整数のサイズ (通常は 32 ビットか 64 ビット) を仮定しますが、 これを Perl がビルドされたコンパイラが対応している標準 C の型の一つで 上書きできます:

   hh          interpret integer as C type "char" or "unsigned
               char" on Perl 5.14 or later
   h           interpret integer as C type "short" or
               "unsigned short"
   j           interpret integer as C type "intmax_t" on Perl
               5.14 or later; and prior to Perl 5.30, only with
               a C99 compiler (unportable)
   l           interpret integer as C type "long" or
               "unsigned long"
   q, L, or ll interpret integer as C type "long long",
               "unsigned long long", or "quad" (typically
               64-bit integers)
   t           interpret integer as C type "ptrdiff_t" on Perl
               5.14 or later
   z           interpret integer as C types "size_t" or
               "ssize_t" on Perl 5.14 or later
   hh          Perl 5.14 以降で整数を C の "char" または "unsigned char"
               型として解釈する
   h           整数を C の "char" または "unsigned char" 型として解釈する
   j           Perl 5.14 以降 Perl 5.30 以前の C99 コンパイラのみで整数を
               C の "intmax_t" 型として解釈する (移植性なし)
   l           整数を C の "long" または "unsigned long" と解釈する
   h           整数を C の "short" または "unsigned short" と解釈する
   q, L or ll  整数を C の "long long", "unsigned long long",
               "quads"(典型的には 64 ビット整数) のどれかと解釈する
   t           Perl 5.14 以降で整数を C の "ptrdiff_t" 型として解釈する
   z           Perl 5.14 以降で整数を C の "size_t" 型または "ssize_t" 型
               として解釈する

Note that, in general, using the l modifier (for example, when writing "%ld" or "%lu" instead of "%d" and "%u") is unnecessary when used from Perl code. Moreover, it may be harmful, for example on Windows 64-bit where a long is 32-bits.

一般的に、l 修飾子を使う (例えば、"%d""%u" ではなく "%ld""%lu" と書く) ことは、Perl のコードから使われる場合は 不要であることに注意してください。 さらに、例えば long が 32 ビットのときの 64 ビット Windows のように、 有害な場合もあります。

As of 5.14, none of these raises an exception if they are not supported on your platform. However, if warnings are enabled, a warning of the printf warning class is issued on an unsupported conversion flag. Should you instead prefer an exception, do this:

5.14 から、プラットフォームがこれらに対応していないときでも例外が 発生しなくなりました。 しかし、もし警告が有効になっているなら、 非対応変換フラグに関して printf 警告クラスの警告が発生します。 例外の方がお好みなら、以下のようにします:

    use warnings FATAL => "printf";

If you would like to know about a version dependency before you start running the program, put something like this at its top:

プログラムの実行開始前にバージョン依存について知りたいなら、先頭に 以下のようなものを書きます:

    use v5.14;  # for hh/j/t/z/ printf modifiers

You can find out whether your Perl supports quads via Config:

Perl が 64 ビット整数に対応しているかどうかは Config を使って 調べられます:

    use Config;
    if ($Config{use64bitint} eq "define"
        || $Config{longsize} >= 8) {
        print "Nice quads!\n";
    }

For floating-point conversions (e f g E F G), numbers are usually assumed to be the default floating-point size on your platform (double or long double), but you can force "long double" with q, L, or ll if your platform supports them. You can find out whether your Perl supports long doubles via Config:

浮動小数点数変換 (e f g E F G) では、普通はプラットフォームのデフォルトの 不動小数点数のサイズ (double か long double) を仮定しますが、 プラットフォームが対応しているなら、q, L, ll に対して "long double" を強制できます。 Perl が long double に対応しているかどうかは Config を使って 調べられます:

    use Config;
    print "long doubles\n" if $Config{d_longdbl} eq "define";

You can find out whether Perl considers "long double" to be the default floating-point size to use on your platform via Config:

Perl が "long double" をデフォルトの浮動小数点数として扱っているかどうかは Config を使って調べられます:

    use Config;
    if ($Config{uselongdouble} eq "define") {
        print "long doubles by default\n";
    }

It can also be that long doubles and doubles are the same thing:

long double と double が同じ場合もあります:

        use Config;
        ($Config{doublesize} == $Config{longdblsize}) &&
                print "doubles are long doubles\n";

The size specifier V has no effect for Perl code, but is supported for compatibility with XS code. It means "use the standard size for a Perl integer or floating-point number", which is the default.

サイズ指定子 V は Perl のコードには何の影響もありませんが、これは XS コードとの互換性のために対応しています。 これは「Perl 整数 (または浮動小数点数) として標準的なサイズを使う」ことを 意味し、これはデフォルトです。

order of arguments

(引数の順序)

Normally, sprintf takes the next unused argument as the value to format for each format specification. If the format specification uses * to require additional arguments, these are consumed from the argument list in the order they appear in the format specification before the value to format. Where an argument is specified by an explicit index, this does not affect the normal order for the arguments, even when the explicitly specified index would have been the next argument.

通常、sprintf は各フォーマット指定について、 使われていない次の引数を フォーマットする値として使います。 追加の引数を要求するためにフォーマット指定 * を使うと、 これらはフォーマットする値の のフォーマット指定に現れる順番に 引数リストから消費されます。 引数の位置が明示的なインデックスを使って指定された場合、 (明示的に指定したインデックスが次の引数の場合でも) これは通常の引数の順番に影響を与えません。

So:

それで:

    printf "<%*.*s>", $a, $b, $c;

uses $a for the width, $b for the precision, and $c as the value to format; while:

とすると $a を幅に、$b を精度に、$c をフォーマットの値に 使います; 一方:

  printf '<%*1$.*s>', $a, $b;

would use $a for the width and precision, and $b as the value to format.

とすると $a を幅と精度に、$b をフォーマットの値に使います。

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"

If use locale (including use locale ':not_characters') is in effect and POSIX::setlocale has been called, the character used for the decimal separator in formatted floating-point numbers is affected by the LC_NUMERIC locale. See perllocale and POSIX.

(use locale ':not_characters' を含む)use locale が有効で、 POSIX::setlocale が呼び出されている場合、 フォーマットされた浮動小数点数の小数点として使われる文字は LC_NUMERIC ロケールの影響を受けます。 perllocalePOSIX を参照してください。