perl-5.38.0
pack TEMPLATE,LIST

Takes a LIST of values and converts it into a string using the rules given by the TEMPLATE. The resulting string is the concatenation of the converted values. Typically, each converted value looks like its machine-level representation. For example, on 32-bit machines an integer may be represented by a sequence of 4 bytes, which will in Perl be presented as a string that's 4 characters long.

LIST の値を TEMPLATE で与えられたルールを用いて文字列に変換します。 結果の文字列は変換した値を連結したものです。 典型的には、それぞれの変換された値はマシンレベルの表現のように見えます。 例えば、32-bit マシンでは、整数は 4 バイトで表現されるので、 Perl では 4 文字の文字列で表現されます。

See perlpacktut for an introduction to this function.

この関数の説明については perlpacktut を参照してください。

The TEMPLATE is a sequence of characters that give the order and type of values, as follows:

TEMPLATE は、以下のような値の型と順番を指定する文字を並べたものです:

    a  A string with arbitrary binary data, will be null padded.
    A  A text (ASCII) string, will be space padded.
    Z  A null-terminated (ASCIZ) string, will be null padded.
    a  任意のバイナリデータを含む文字列、ヌル文字で埋める。
    A  テキスト (ASCII) 文字列、スペース文字で埋める。
    Z  ヌル文字終端 (ASCIZ) 文字列、ヌル文字で埋める。
    b  A bit string (ascending bit order inside each byte,
       like vec()).
    B  A bit string (descending bit order inside each byte).
    h  A hex string (low nybble first).
    H  A hex string (high nybble first).
    b  ビット列 (バイトごとに昇ビット順、vec() と同じ)。
    B  ビット列 (バイトごとに降ビット順)。
    h  16 進数文字列 (低位ニブルが先)。
    H  16 進数文字列 (高位ニブルが先)。
    c  A signed char (8-bit) value.
    C  An unsigned char (octet) value.
    W  An unsigned char value (can be greater than 255).
    c  signed char (8 ビット) 値。
    C  unsigned char (オクテット) 値。
    W  unsigned char 値 (255 より大きいかもしれません)。
    s  A signed short (16-bit) value.
    S  An unsigned short value.
    s  signed short (16 ビット) 値。
    S  unsigned short 値。
    l  A signed long (32-bit) value.
    L  An unsigned long value.
    l  signed long (32 ビット) 値。
    L  unsigned long 値。
    q  A signed quad (64-bit) value.
    Q  An unsigned quad value.
         (Quads are available only if your system supports 64-bit
          integer values _and_ if Perl has been compiled to support
          those.  Raises an exception otherwise.)
    q  符号付き 64 ビット整数。
    Q  符号なし 64 ビット整数。
      (64 ビット整数は、システムが 64 ビット整数に対応していて、かつ Perl が
       64 ビット整数対応としてコンパイルされている場合にのみ使用可能です。
           それ以外の場合は例外が発生します。)
    i  A signed integer value.
    I  An unsigned integer value.
         (This 'integer' is _at_least_ 32 bits wide.  Its exact
          size depends on what a local C compiler calls 'int'.)
    i  signed int 値。
    I  unsigned int 値。
       (ここでの 'integer' は 「最低」 32 ビット幅です。正確なサイズは
        ローカルの C コンパイラの 'int' のサイズに依存します。)
    n  An unsigned short (16-bit) in "network" (big-endian) order.
    N  An unsigned long (32-bit) in "network" (big-endian) order.
    v  An unsigned short (16-bit) in "VAX" (little-endian) order.
    V  An unsigned long (32-bit) in "VAX" (little-endian) order.
    n  "network" 順序 (ビッグエンディアン) の unsigned short (16 ビット)。
    N  "network" 順序 (ビッグエンディアン) の unsigned long (32 ビット)。
    v  "VAX" 順序 (リトルエンディアン) の unsigned short (16 ビット)。
    V  "VAX" 順序 (リトルエンディアン) の unsigned long (32 ビット)。
    j  A Perl internal signed integer value (IV).
    J  A Perl internal unsigned integer value (UV).
    j  Perl 内部符号付き整数 (IV)。
    J  Perl 内部符号なし整数 (UV)。
    f  A single-precision float in native format.
    d  A double-precision float in native format.
    f  機種依存の単精度浮動小数点数。
    d  機種依存の倍精度浮動小数点数。
    F  A Perl internal floating-point value (NV) in native format
    D  A float of long-double precision in native format.
         (Long doubles are available only if your system supports
          long double values. Raises an exception otherwise.
          Note that there are different long double formats.)
    F  ネイティブフォーマットの Perl 内部浮動小数点数 (NV)
    D  ネイティブフォーマットの長い倍精度浮動小数点数(long double)。
      (long double は、システムが long double に対応している場合にのみ
          使用可能です。それ以外の場合は例外が発生します。
          long double 型式の場合は異なることに注意してください。)
    p  A pointer to a null-terminated string.
    P  A pointer to a structure (fixed-length string).
    p  ヌル文字で終端する文字列へのポインタ。
    P  構造体 (固定長文字列) へのポインタ。
    u  A uuencoded string.
    U  A Unicode character number.  Encodes to a character in char-
       acter mode and UTF-8 (or UTF-EBCDIC in EBCDIC platforms) in
       byte mode.  Also on EBCDIC platforms, the character number will
       be the native EBCDIC value for character numbers below 256.
       This allows most programs using this feature to not have to
       care which type of platform they are running on.
    u  uuencode 文字列。
    U  Unicode 文字番号。文字モードでは文字に、バイトモードなら UTF-8 に
       (EBCDIC システムでは UTF-EBCDIC に)エンコードされます。
       また EBCDIC プラットフォームでは、文字番号が 256 より下の場合は
       EBCDIC にネイティブな値です。
       これにより、この機能を使うほとんどのプログラムで、どの種類の
       プラットフォームで実行されるかを気にする必要がなくなります。
    w  A BER compressed integer (not an ASN.1 BER, see perlpacktut
       for details).  Its bytes represent an unsigned integer in
       base 128, most significant digit first, with as few digits
       as possible.  Bit eight (the high bit) is set on each byte
       except the last.
    w  A BER 圧縮変数(ASN.1 BER ではありません; 詳細については perlpacktut を
       参照してください)。このバイト列はできるだけ少ない桁数で表現された
       128 を基とした符号なし整数で、最上位ビットから順に並びます。
       最後のバイト以外の各バイトのビット 8 (上位ビット) がセットされます。
    x  A null byte (a.k.a ASCII NUL, "\000", chr(0))
    X  Back up a byte.
    @  Null-fill or truncate to absolute position, counted from the
       start of the innermost ()-group.
    .  Null-fill or truncate to absolute position specified by
       the value.
    (  Start of a ()-group.
    x  ヌル文字 (つまり ASCII NUL, "\000", chr(0))
    X  1 文字後退。
    @  一番内側の () の組の開始位置から数えて、絶対位置までヌル文字で
       埋めるか切り詰める。
    .  値で指定した絶対位置までヌル文字で埋めるか切り詰める。
    (  () の組の開始。

One or more modifiers below may optionally follow certain letters in the TEMPLATE (the second column lists letters for which the modifier is valid):

以下に示す一つまたは複数の修飾子を、TEMPLATE の文字のいくつかにオプションで 付けることができます(表の 2 列目は、その修飾子が有効な文字です):

    !   sSlLiI     Forces native (short, long, int) sizes instead
                   of fixed (16-/32-bit) sizes.
    !   sSlLiI     固定の(16/32 ビット)サイズではなく、ネイティブな
                   (short, long, int)サイズを強制する。
    !   xX         Make x and X act as alignment commands.
    !   xX         x と X をアライメントコマンドとして振舞わせる。
    !   nNvV       Treat integers as signed instead of unsigned.
    !   nNvV       整数を符号なしではなく符号付きとして扱わせる。
    !   @.         Specify position as byte offset in the internal
                   representation of the packed string.  Efficient
                   but dangerous.
    !   @.         pack された内部表現のバイトオフセットとして位置を指定する。
                   効率的ですが危険です。
    >   sSiIlLqQ   Force big-endian byte-order on the type.
        jJfFdDpP   (The "big end" touches the construct.)
    >   sSiIlLqQ   これらの型のバイト順をビッグエンディアンに強制します。
        jJfFdDpP   (「大きい端」が構造に触れています。)
    <   sSiIlLqQ   Force little-endian byte-order on the type.
        jJfFdDpP   (The "little end" touches the construct.)
    <   sSiIlLqQ   これらの型のバイト順をリトルエンディアンに強制します。
        jJfFdDpP   (「小さい端」が構造に触れています。)

The > and < modifiers can also be used on () groups to force a particular byte-order on all components in that group, including all its subgroups.

>< の修飾子は ()-グループでも使えます; この場合はそのグループと全ての副グループ内の全ての要素を特定のバイト順に 強制します。

The following rules apply:

以下の条件が適用されます:

  • Each letter may optionally be followed by a number indicating the repeat count. A numeric repeat count may optionally be enclosed in brackets, as in pack("C[80]", @arr). The repeat count gobbles that many values from the LIST when used with all format types other than a, A, Z, b, B, h, H, @, ., x, X, and P, where it means something else, described below. Supplying a * for the repeat count instead of a number means to use however many items are left, except for:

    これらの文字の後には、繰り返し数を示す数字を付けることができます。 数値の繰り返し数は pack "C[80]", @arr のように大かっこで 囲むこともできます。 a, A, Z, b, B, h, H, @, ., x, X, P 以外の全ての型では、LIST から繰り返し数の値を取り出して使います。 繰り返し数に * を指定すると、以下の例外を除いて、 その時点で残っているすべての要素を意味します。

    • @, x, and X, where it is equivalent to 0.

      @, x, X では 0 と等価です。

    • <.>, where it means relative to the start of the string.

      <.> では文字列の先頭からの相対位置を意味します。

    • u, where it is equivalent to 1 (or 45, which here is equivalent).

      u では 1 (あるいはここでは 45 でも等価です) と等価です。

    One can replace a numeric repeat count with a template letter enclosed in brackets to use the packed byte length of the bracketed template for the repeat count.

    このテンプレートでパックされたバイト長を繰り返し数として使うために、 大かっこで囲まれたテンプレートで数値の繰り返し数を置き換えることが できます。

    For example, the template x[L] skips as many bytes as in a packed long, and the template "$t X[$t] $t" unpacks twice whatever $t (when variable-expanded) unpacks. If the template in brackets contains alignment commands (such as x![d]), its packed length is calculated as if the start of the template had the maximal possible alignment.

    例えば、テンプレート x[L] は long でパックされたバイト数分だけスキップし、 テンプレート "$t X[$t] $t" は $t (変数展開された場合)を unpack したものの 2 倍を unpack します。 (x![d] のように) 大かっこにアライメントコマンドが含まれている場合、 パックされた長さは、テンプレートの先頭で最大限可能なアライメントを 持っているものとして計算されます。

    When used with Z, a * as the repeat count is guaranteed to add a trailing null byte, so the resulting string is always one byte longer than the byte length of the item itself.

    Z で、繰り返し数として * が使われた場合、末尾にヌルバイトが 保証されるので、結果の文字列は常にアイテム自身のバイト長よりも 1 バイト 長くなります。

    When used with @, the repeat count represents an offset from the start of the innermost () group.

    @ で使うと、繰り返し数は一番内側の () グループの先頭からのオフセットを 表現します。

    When used with ., the repeat count determines the starting position to calculate the value offset as follows:

    . で使われると、繰り返し数は以下のようにして、 値のオフセットを計算するための開始位置を決定するために使われます。

    • If the repeat count is 0, it's relative to the current position.

      繰り返し数が 0 なら、現在位置からの相対位置となります。

    • If the repeat count is *, the offset is relative to the start of the packed string.

      繰り返し数が * なら、オフセットは pack された文字列の先頭からの 相対位置です。

    • And if it's an integer n, the offset is relative to the start of the nth innermost ( ) group, or to the start of the string if n is bigger then the group level.

      そして整数 n なら、オフセットは一番内側から n 番目の ( ) グループの 先頭、あるいは n がグループレベルより大きい場合は文字列の先頭からの 相対位置です。

    The repeat count for u is interpreted as the maximal number of bytes to encode per line of output, with 0, 1 and 2 replaced by 45. The repeat count should not be more than 65.

    u での繰り返し回数は、出力行毎に最大何バイトまでをエンコードするかを 示します; 0, 1, 2 は 45 として扱われます。 繰り返し数は 65 を超えてはなりません。

  • The a, A, and Z types gobble just one value, but pack it as a string of length count, padding with nulls or spaces as needed. When unpacking, A strips trailing whitespace and nulls, Z strips everything after the first null, and a returns data with no stripping at all.

    a, A, Z という型を使うと、値を一つだけ取り出して使いますが、 繰り返し数で示す長さの文字列となるように、必要に応じてヌル文字か スペース文字を付け足します。 unpack するとき、A は後続の空白やヌル文字を取り除きます; Z は最初の ヌル文字以降の全てを取り除きます; a はデータを取り除くことなく そのまま返します。

    If the value to pack is too long, the result is truncated. If it's too long and an explicit count is provided, Z packs only $count-1 bytes, followed by a null byte. Thus Z always packs a trailing null, except when the count is 0.

    pack する値が長すぎる場合、結果は切り詰められます。 長すぎてかつ明示的に個数が指定されている場合、 Z$count-1 バイトまで pack し、その後にヌルバイトがつきます。 従って、Z は、繰り返し数が 0 の場合を除いて、常に末尾にヌルバイトが つきます。

  • Likewise, the b and B formats pack a string that's that many bits long. Each such format generates 1 bit of the result. These are typically followed by a repeat count like B8 or B64.

    同様に、bB は、繰り返し数で示すビット長のビット列に pack します。 これらの各文字は結果の 1 ビットを生成します。 これらは典型的には B8B64 のような繰り返しカウントが引き続きます。

    Each result bit is based on the least-significant bit of the corresponding input character, i.e., on ord($char)%2. In particular, characters "0" and "1" generate bits 0 and 1, as do characters "\000" and "\001".

    結果ビットのそれぞれは対応する入力文字の最下位ビットを基にします (つまり ord($char)%2)。 特に、文字 "0""1" は文字 "\000""\001" と同様に、 ビット 0 と 1 を生成します。

    Starting from the beginning of the input string, each 8-tuple of characters is converted to 1 character of output. With format b, the first character of the 8-tuple determines the least-significant bit of a character; with format B, it determines the most-significant bit of a character.

    pack() の入力文字列の先頭から始めて、8 タプル毎に 1 文字の出力に変換されます。 b フォーマットでは 8 タプルの最初の文字が出力の最下位ビットとなります; B フォーマットでは出力の最上位ビットとなります。

    If the length of the input string is not evenly divisible by 8, the remainder is packed as if the input string were padded by null characters at the end. Similarly during unpacking, "extra" bits are ignored.

    もし入力文字列の長さが 8 で割り切れない場合、余りの部分は入力文字列の 最後にヌル文字がパッディングされているものとしてパックされます。 同様に、unpack 中は「余分な」ビットは無視されます。

    If the input string is longer than needed, remaining characters are ignored.

    入力文字列が必要な分よりも長い場合、余分な文字は無視されます。

    A * for the repeat count uses all characters of the input field. On unpacking, bits are converted to a string of 0s and 1s.

    繰り返し数として * が指定されると、入力フィールドの全ての文字が使われます。 unpack 時にはビット列は 01 の文字列に変換されます。

  • The h and H formats pack a string that many nybbles (4-bit groups, representable as hexadecimal digits, "0".."9" "a".."f") long.

    hH は、多ニブル長(16 進文字である "0".."9" "a".."f" で 表現可能な 4 ビットグループ)のニブル列に pack します。

    For each such format, pack generates 4 bits of result. With non-alphabetical characters, the result is based on the 4 least-significant bits of the input character, i.e., on ord($char)%16. In particular, characters "0" and "1" generate nybbles 0 and 1, as do bytes "\000" and "\001". For characters "a".."f" and "A".."F", the result is compatible with the usual hexadecimal digits, so that "a" and "A" both generate the nybble 0xA==10. Use only these specific hex characters with this format.

    このようなフォーマット文字のそれぞれについて、pack は 結果の 4 ビットを生成します。 英字でない文字の場合、結果は入力文字の下位 4 ビットを 基にします(つまり ord($char)%16)。 特に、文字 "0""1" はバイト "\000""\001" と同様に ニブル 0 と 1 を生成します。 文字 "a".."f""A".."F" の場合は結果は通常の 16 進数と同じ結果に なるので、"a""A" はどちらも ニブル 0xa==10 を生成します。 これらの 16 進文字はこの特定のフォーマットでだけ使ってください。

    Starting from the beginning of the template to pack, each pair of characters is converted to 1 character of output. With format h, the first character of the pair determines the least-significant nybble of the output character; with format H, it determines the most-significant nybble.

    pack のテンプレートの先頭から始めて、2 文字毎に 1 文字の出力に変換されます。 h フォーマットでは 1 文字目が出力の最下位ニブルとなり、 H フォーマットでは出力の最上位ニブルとなります。

    If the length of the input string is not even, it behaves as if padded by a null character at the end. Similarly, "extra" nybbles are ignored during unpacking.

    入力文字列の長さが偶数でない場合、最後にヌル文字でパッディングされて いるかのように振る舞います。 同様に、unpack 中は「余分な」ニブルは無視されます。

    If the input string is longer than needed, extra characters are ignored.

    入力文字列が必要な分より長い場合、余分な部分は無視されます。

    A * for the repeat count uses all characters of the input field. For unpack, nybbles are converted to a string of hexadecimal digits.

    繰り返し数として * が指定されると、入力フィールドの全ての文字が使われます。 unpack 時にはニブルは 16 進数の文字列に 変換されます。

  • The p format packs a pointer to a null-terminated string. You are responsible for ensuring that the string is not a temporary value, as that could potentially get deallocated before you got around to using the packed result. The P format packs a pointer to a structure of the size indicated by the length. A null pointer is created if the corresponding value for p or P is undef; similarly with unpack, where a null pointer unpacks into undef.

    p は、ヌル文字終端文字列へのポインタを pack します。 文字列が一時的な値でない(つまり pack された結果を使う前に文字列が 解放されない) ことに責任を持つ必要があります。 P は、指定した長さの構造体へのポインタを pack します。 p または P に対応する値が undef だった場合、 ヌルポインタが作成されます; ヌルポインタが undef に unpack される unpack と同様です。

    If your system has a strange pointer size--meaning a pointer is neither as big as an int nor as big as a long--it may not be possible to pack or unpack pointers in big- or little-endian byte order. Attempting to do so raises an exception.

    システムのポインタが変わったサイズの場合--つまり、int の大きさでも long の大きさでもない場合--ポインタをビッグエンディアンやリトルエンディアンの バイト順で pack や unpack することはできません。 そうしようとすると例外が発生します。

  • The / template character allows packing and unpacking of a sequence of items where the packed structure contains a packed item count followed by the packed items themselves. This is useful when the structure you're unpacking has encoded the sizes or repeat counts for some of its fields within the structure itself as separate fields.

    / テンプレート文字は、アイテムの数の後にアイテムそのものが入っている形の アイテム列を pack 及び unpack します。 これは、unpack したい構造体が、サイズや繰り返し数が構造体自身の中に 独立したフィールドとしてエンコードされている場合に有効です。

    For pack, you write length-item/sequence-item, and the length-item describes how the length value is packed. Formats likely to be of most use are integer-packing ones like n for Java strings, w for ASN.1 or SNMP, and N for Sun XDR.

    pack では length-item/string-item の 形になり、 length-item は長さの値がどのように pack されているかを指定します。 もっともよく使われるのは Java 文字列 のための n、ASN.1 や SNMP のための w、Sun XDR のための N といった整数型です。

    For pack, sequence-item may have a repeat count, in which case the minimum of that and the number of available items is used as the argument for length-item. If it has no repeat count or uses a '*', the number of available items is used.

    pack では、sequence-item は繰り返し数を 持つことがあり、その場合はその最小値と利用可能なアイテムの数は length-item のための引数として使われます。 繰り返し数がなかったり、'*' を使うと、利用可能なアイテムの数が使われます。

    For unpack, an internal stack of integer arguments unpacked so far is used. You write /sequence-item and the repeat count is obtained by popping off the last element from the stack. The sequence-item must not have a repeat count.

    unpack では、今まで unpack した数値引数の 内部スタックが使われます。 /sequence-item と書いて、繰り返し数はスタックから最後の要素を 取り出すことで得ます。 sequence-item は繰り返し数を持っていてはいけません。

    If sequence-item refers to a string type ("A", "a", or "Z"), the length-item is the string length, not the number of strings. With an explicit repeat count for pack, the packed string is adjusted to that length. For example:

    sequence-item が文字列型 ("A", "a", "Z") を参照している場合、 length-item は文字列の数ではなく、文字列の長さです。 pack で明示的な繰り返し数があると、pack された文字列は与えられた 長さに調整されます。 例えば:

     This code:                             gives this result:
    
     unpack("W/a", "\004Gurusamy")          ("Guru")
     unpack("a3/A A*", "007 Bond  J ")      (" Bond", "J")
     unpack("a3 x2 /A A*", "007: Bond, J.") ("Bond, J", ".")
    
     pack("n/a* w/a","hello,","world")     "\000\006hello,\005world"
     pack("a/W2", ord("a") .. ord("z"))    "2ab"

    The length-item is not returned explicitly from unpack.

    length-itemunpack から明示的には 返されません。

    Supplying a count to the length-item format letter is only useful with A, a, or Z. Packing with a length-item of a or Z may introduce "\000" characters, which Perl does not regard as legal in numeric strings.

    length-item 文字に繰り返し数をつけるのは、 文字が A, a, Z でない限りは有用ではありません。 aZlength-item として pack すると "\000" 文字が 出力されることがあり、Perl はこれを有効な数値文字列として認識しません。

  • The integer types s, S, l, and L may be followed by a ! modifier to specify native shorts or longs. As shown in the example above, a bare l means exactly 32 bits, although the native long as seen by the local C compiler may be larger. This is mainly an issue on 64-bit platforms. You can see whether using ! makes any difference this way:

    s, S, l, L の整数タイプに引き続いて ! 修飾子を つけることで、ネイティブの short や long を指定できます。 上述のように、l は正確に 32 ビットですが、ネイティブな (ローカルな C コンパイラによる)long はもっと大きいかもしれません。 これは主に 64 ビットプラットフォームで意味があります。 ! を使うことによって違いがあるかどうかは以下のようにして調べられます:

        printf "format s is %d, s! is %d\n",
            length pack("s"), length pack("s!");
    
        printf "format l is %d, l! is %d\n",
            length pack("l"), length pack("l!");

    i! and I! are also allowed, but only for completeness' sake: they are identical to i and I.

    i!I! も動作しますが、単に完全性のためだけです; これは i 及び I と同じです。

    The actual sizes (in bytes) of native shorts, ints, longs, and long longs on the platform where Perl was built are also available from the command line:

    Perl がビルドされたプラットフォームでの short, int, long, long long の 実際の(バイト数での)サイズはコマンドラインから:

        $ perl -V:{short,int,long{,long}}size
        shortsize='2';
        intsize='4';
        longsize='4';
        longlongsize='8';

    or programmatically via the Config module:

    あるいは Config モジュールからプログラムで:

           use Config;
           print $Config{shortsize},    "\n";
           print $Config{intsize},      "\n";
           print $Config{longsize},     "\n";
           print $Config{longlongsize}, "\n";

    $Config{longlongsize} is undefined on systems without long long support.

    システムが long long に対応していない場合は $Config{longlongsize} は 未定義値になります。

  • The integer formats s, S, i, I, l, L, j, and J are inherently non-portable between processors and operating systems because they obey native byteorder and endianness. For example, a 4-byte integer 0x12345678 (305419896 decimal) would be ordered natively (arranged in and handled by the CPU registers) into bytes as

    整数フォーマット s, S, i, I, l, L, j, J は ネイティブなバイト順序とエンディアンに従っているため、 本質的にプロセッサ間や OS 間で移植性がありません。 例えば 4 バイトの整数 0x12345678 (10 進数では 305419896) は 内部では(CPU レジスタによって変換され扱われる形では) 以下のようなバイト列に並べられます:

        0x12 0x34 0x56 0x78  # big-endian
        0x78 0x56 0x34 0x12  # little-endian

    Basically, Intel and VAX CPUs are little-endian, while everybody else, including Motorola m68k/88k, PPC, Sparc, HP PA, Power, and Cray, are big-endian. Alpha and MIPS can be either: Digital/Compaq uses (well, used) them in little-endian mode, but SGI/Cray uses them in big-endian mode.

    基本的に、Intel と VAX の CPU はリトルエンディアンです; 一方、 Motorola m68k/88k, PPC, Sparc, HP PA, Power, Cray などを含むその他の全ては ビッグエンディアンです。 Alpha と MIPS は両方ともあります: Digital/Compaq はリトルエンディアンモードで 使っています (えーと、いました) が、SGI/Cray はビッグエンディアンモードで 使っています。

    The names big-endian and little-endian are comic references to the egg-eating habits of the little-endian Lilliputians and the big-endian Blefuscudians from the classic Jonathan Swift satire, Gulliver's Travels. This entered computer lingo via the paper "On Holy Wars and a Plea for Peace" by Danny Cohen, USC/ISI IEN 137, April 1, 1980.

    ビッグエンディアンリトルエンディアン の名前は、 ジョナサン=スウィフトによる風刺小説の古典 ガリバー旅行記 での、卵を 小さい方からむくリリパット国と大きい方からむくブレフスキュ国から 取られています。 "On Holy Wars and a Plea for Peace" by Danny Cohen, USC/ISI IEN 137, April 1, 1980 の文書からコンピュータ用語として取り入れられました。

    Some systems may have even weirder byte orders such as

    以下のような、さらに変わったバイト順序を持つシステムもあるかもしれません:

       0x56 0x78 0x12 0x34
       0x34 0x12 0x78 0x56

    These are called mid-endian, middle-endian, mixed-endian, or just weird.

    これらは mid-endian, middle-endian, mixed-endian あるいは単におかしなものと 呼ばれます。

    You can determine your system endianness with this incantation:

    システムの設定は以下のようにして調べられます:

       printf("%#02x ", $_) for unpack("W*", pack L=>0x12345678);

    The byteorder on the platform where Perl was built is also available via Config:

    Perl がビルドされたプラットフォームでのバイト順序は Config 経由か:

        use Config;
        print "$Config{byteorder}\n";

    or from the command line:

    あるいはコマンドラインで:

        $ perl -V:byteorder

    Byteorders "1234" and "12345678" are little-endian; "4321" and "87654321" are big-endian. Systems with multiarchitecture binaries will have "ffff", signifying that static information doesn't work, one must use runtime probing.

    "1234""12345678" はリトルエンディアンです; "4321""87654321" はビッグエンディアンです。 マルチアーキテクチャバイナリを持つシステムは "ffff" となります; これは静的な情報は動作せず、実行時調査を使う必要が あることを示します。

    For portably packed integers, either use the formats n, N, v, and V or else use the > and < modifiers described immediately below. See also perlport.

    移植性のあるパック化された整数がほしい場合は、 n, N, v, V フォーマットを使うか、 直後で説明する >< の修飾子が使えます。 perlport も参照してください。

  • Also floating point numbers have endianness. Usually (but not always) this agrees with the integer endianness. Even though most platforms these days use the IEEE 754 binary format, there are differences, especially if the long doubles are involved. You can see the Config variables doublekind and longdblkind (also doublesize, longdblsize): the "kind" values are enums, unlike byteorder.

    また、浮動小数点数にもエンディアンがあります。 通常は(但し常にではありません)これは整数のエンディアンと同じです。 最近のほとんどのプラットフォームが IEEE 754 バイナリ形式を使っているにも 関わらず、(特に long double 関連で) 相違点があります。 Config 変数 doublekindlongdblkind (および doublesize, longdblsize) を参照できます: "kind" 値は byteorder と異なり、 順序値です。

    Portability-wise the best option is probably to keep to the IEEE 754 64-bit doubles, and of agreed-upon endianness. Another possibility is the "%a") format of printf.

    移植性を考慮した最良の選択肢はおそらく、IEEE 754 64-bit double と同意した エンディアンを維持することです。 もう一つの可能性は printf"%a" 型式です。

  • Starting with Perl 5.10.0, integer and floating-point formats, along with the p and P formats and () groups, may all be followed by the > or < endianness modifiers to respectively enforce big- or little-endian byte-order. These modifiers are especially useful given how n, N, v, and V don't cover signed integers, 64-bit integers, or floating-point values.

    Perl 5.10.0 から、pP フォーマットや () グループと同様、 全ての整数と浮動小数点数のフォーマットは、>< の エンディアン修飾子をつけることで、それぞれ ビッグエンディアンとリトルエンディアンに強制させることができます。 n, N, v, V は符号付き整数、64 ビット整数、浮動小数点数に 対応していないので、これは特に有用です。

    Here are some concerns to keep in mind when using an endianness modifier:

    エンディアン修飾子を使うときに心に留めておくべきことを記します:

    • Exchanging signed integers between different platforms works only when all platforms store them in the same format. Most platforms store signed integers in two's-complement notation, so usually this is not an issue.

      異なったプラットフォームで符号付き整数を交換することは、全ての プラットフォームで同じフォーマットで保存されている場合にのみうまくいきます。 ほとんどのプラットフォームでは符号付き整数は 2 の補数記法で保存するので、 普通はこれは問題になりません。

    • The > or < modifiers can only be used on floating-point formats on big- or little-endian machines. Otherwise, attempting to use them raises an exception.

      >< の修飾子はビッグエンディアンやリトルエンディアンの マシンでの浮動小数点フォーマットでのみ使えます。 それ以外では、そのようなことをすると例外が発生します。

    • Forcing big- or little-endian byte-order on floating-point values for data exchange can work only if all platforms use the same binary representation such as IEEE floating-point. Even if all platforms are using IEEE, there may still be subtle differences. Being able to use > or < on floating-point values can be useful, but also dangerous if you don't know exactly what you're doing. It is not a general way to portably store floating-point values.

      データ交換のために浮動小数点数のバイト順をビッグエンディアンかリトル エンディアンに強制することは、全てのプラットフォームが IEEE 浮動小数点フォーマットのような同じバイナリ表現の場合にのみ うまくいきます。 たとえ全てのプラットフォームが IEEE を使っていても、そこには微妙な違いが あるかもしれません。 浮動小数点数に >< が使えることは便利な場合がありますが、 もし自分が何をしているかを正確に理解していなければ、危険です。 移植性のある浮動小数点数の保存のための一般的な方法はありません。

    • When using > or < on a () group, this affects all types inside the group that accept byte-order modifiers, including all subgroups. It is silently ignored for all other types. You are not allowed to override the byte-order within a group that already has a byte-order modifier suffix.

      () グループで >< を使うと、これは、副グループを 含む全ての型のうち、バイト順修飾子を受け入れる全てのものに影響与えます。 その他の型については沈黙のうちに無視されます。 既にバイト順接尾辞を持っているグループ内のバイト順を上書きすることは できません。

  • Real numbers (floats and doubles) are in native machine format only. Due to the multiplicity of floating-point formats and the lack of a standard "network" representation for them, no facility for interchange has been made. This means that packed floating-point data written on one machine may not be readable on another, even if both use IEEE floating-point arithmetic (because the endianness of the memory representation is not part of the IEEE spec). See also perlport.

    実数 (float と double) は、機種依存のフォーマットしかありません。 いろんな浮動小数点数のフォーマットが在り、標準的な "network" 表現といったものが ないため、データ交換のための機能は用意してありません。 つまり、あるマシンで pack した浮動小数点数は、別のマシンでは 読めないかもしれないということです; たとえ双方で IEEE フォーマットの 浮動小数点数演算を行なっていてもです (IEEE の仕様では、メモリ表現上の バイト順序までは、規定されていないからです)。 perlport も参照してください。

    If you know exactly what you're doing, you can use the > or < modifiers to force big- or little-endian byte-order on floating-point values.

    もし何をしようとしているのかを 正確に 理解しているなら、浮動小数点数の バイト順をビッグエンディアンやリトルエンディアンに強制するために、 >< の修飾子が使えます。

    Because Perl uses doubles (or long doubles, if configured) internally for all numeric calculation, converting from double into float and thence to double again loses precision, so unpack("f", pack("f", $foo)) will not in general equal $foo.

    Perl では、すべての数値演算のために、内部的に double (または設定によっては long double) を使用しているので、double から float へ変換し、それから再び double に戻すと精度が落ちることになり、unpack("f", pack("f", $foo)) は、 一般には $foo と同じではありません。

  • Pack and unpack can operate in two modes: character mode (C0 mode) where the packed string is processed per character, and UTF-8 byte mode (U0 mode) where the packed string is processed in its UTF-8-encoded Unicode form on a byte-by-byte basis. Character mode is the default unless the format string starts with U. You can always switch mode mid-format with an explicit C0 or U0 in the format. This mode remains in effect until the next mode change, or until the end of the () group it (directly) applies to.

    pack と unpack は二つのモードで操作します: pack された文字列を文字単位で 処理する文字モード (C0 モード) と、pack された文字列を、バイト毎に、 その UTF-8 エンコードされた形式で処理するUTF-8 モード (U0 モード) です。 文字モードはフォーマット文字列が U で始まっていない限りはデフォルトです。 モードはフォーマット中に明示的に C0 または U0 と書くことでいつでも 切り替えられます。 モードは次のモードに切り替えられるか、(直接)適用された () グループが 終了するまで有効です。

    Using C0 to get Unicode characters while using U0 to get non-Unicode bytes is not necessarily obvious. Probably only the first of these is what you want:

    Unicode 文字を取得するのに C0 を使い、 Unicode バイトを取得するのに U0 を使うというのは必ずしも明白ではありません。 おそらく、これらのうち最初のものだけが望みのものでしょう:

        $ perl -CS -E 'say "\x{3B1}\x{3C9}"' |
          perl -CS -ne 'printf "%v04X\n", $_ for unpack("C0A*", $_)'
        03B1.03C9
        $ perl -CS -E 'say "\x{3B1}\x{3C9}"' |
          perl -CS -ne 'printf "%v02X\n", $_ for unpack("U0A*", $_)'
        CE.B1.CF.89
        $ perl -CS -E 'say "\x{3B1}\x{3C9}"' |
          perl -C0 -ne 'printf "%v02X\n", $_ for unpack("C0A*", $_)'
        CE.B1.CF.89
        $ perl -CS -E 'say "\x{3B1}\x{3C9}"' |
          perl -C0 -ne 'printf "%v02X\n", $_ for unpack("U0A*", $_)'
        C3.8E.C2.B1.C3.8F.C2.89

    Those examples also illustrate that you should not try to use pack/unpack as a substitute for the Encode module.

    これらの例は、pack/ unpackEncode モジュールの代わりとして 使おうとするべきではないということも示しています。

  • You must yourself do any alignment or padding by inserting, for example, enough "x"es while packing. There is no way for pack and unpack to know where characters are going to or coming from, so they handle their output and input as flat sequences of characters.

    pack するときに、例えば十分な数の "x" を挿入することによって アライメントやパッディングを行うのは全て自分でしなければなりません。 packunpack は、 文字列がどこへ行くかやどこから来たかを 知る方法はないので、出力と入力をフラットな文字列として扱います。

  • A () group is a sub-TEMPLATE enclosed in parentheses. A group may take a repeat count either as postfix, or for unpack, also via the / template character. Within each repetition of a group, positioning with @ starts over at 0. Therefore, the result of

    () のグループはかっこで囲われた副テンプレートです。 グループは繰り返し数を取ることができます; 接尾辞によるか、 unpack の場合は / テンプレート文字によります。 グループの繰り返し毎に、@ の位置は 0 になります。 従って、以下の結果は:

        pack("@1A((@2A)@3A)", qw[X Y Z])

    is the string "\0X\0\0YZ".

    文字列 "\0X\0\0YZ" です。

  • x and X accept the ! modifier to act as alignment commands: they jump forward or back to the closest position aligned at a multiple of count characters. For example, to pack or unpack a C structure like

    xX にはアライメントコマンドとして ! 修飾子を付けることができます: これは count 文字の倍数のアライメントとなる、もっとも近い位置に移動します。 例えば、以下のような C 構造体を pack または unpack するには

        struct {
            char   c;    /* one signed, 8-bit character */
            double d;
            char   cc[2];
        }

    one may need to use the template c x![d] d c[2]. This assumes that doubles must be aligned to the size of double.

    W x![d] d W[2] というテンプレートを使う必要があるかもしれません。 これは double が double のサイズでアライメントされていることを 仮定しています。

    For alignment commands, a count of 0 is equivalent to a count of 1; both are no-ops.

    アライメントコマンドに対しては、count に 0 を指定するのは count に 1 を指定するのと等価です; どちらも何もしません。

  • n, N, v and V accept the ! modifier to represent signed 16-/32-bit integers in big-/little-endian order. This is portable only when all platforms sharing packed data use the same binary representation for signed integers; for example, when all platforms use two's-complement representation.

    n, N, v, V はビッグ/リトルエンディアンの順序で符号付き 16 または 32 ビット整数で表現するための ! 修飾子を受け入れます。 これは pack されたデータを共有する全てのプラットフォームが 符号付き整数について同じバイナリ表現を使う場合にのみ移植性があります; 例えば、全てのプラットフォームで 2 の補数表現を使う場合です。

  • Comments can be embedded in a TEMPLATE using # through the end of line. White space can separate pack codes from each other, but modifiers and repeat counts must follow immediately. Breaking complex templates into individual line-by-line components, suitably annotated, can do as much to improve legibility and maintainability of pack/unpack formats as /x can for complicated pattern matches.

    TEMPLATE の中の # から行末まではコメントです。 空白は pack コードをそれぞれ分けるために使えますが、修飾子と 繰り返し数は直後に置かなければなりません。 複雑なテンプレートを個々の行単位の要素に分解して適切に注釈をつけると、 複雑なパターンマッチングに対する /x と同じぐらい、pack/unpack フォーマットの読みやすさと保守性が向上します。

  • If TEMPLATE requires more arguments than pack is given, pack assumes additional "" arguments. If TEMPLATE requires fewer arguments than given, extra arguments are ignored.

    TEMPLATE が要求する引数の数が pack が実際に 与えている数より多い場合、 pack は追加の "" 引数があるものと仮定します。 TEMPLATE が要求する引数の数の方が少ない場合、余分の引数は無視されます。

  • Attempting to pack the special floating point values Inf and NaN (infinity, also in negative, and not-a-number) into packed integer values (like "L") is a fatal error. The reason for this is that there simply isn't any sensible mapping for these special values into integers.

    特殊浮動小数点値 InfNaN ((負を含む)無限と非数) を ("L" のような) 整数値に pack しようとすると 致命的エラーとなります。 この理由は、単に特殊値を整数に割り当てられないからです。

Examples:

例:

    $foo = pack("WWWW",65,66,67,68);
    # foo eq "ABCD"
    $foo = pack("W4",65,66,67,68);
    # same thing
    $foo = pack("W4",0x24b6,0x24b7,0x24b8,0x24b9);
    # same thing with Unicode circled letters.
    $foo = pack("U4",0x24b6,0x24b7,0x24b8,0x24b9);
    # same thing with Unicode circled letters.  You don't get the
    # UTF-8 bytes because the U at the start of the format caused
    # a switch to U0-mode, so the UTF-8 bytes get joined into
    # characters
    $foo = pack("C0U4",0x24b6,0x24b7,0x24b8,0x24b9);
    # foo eq "\xe2\x92\xb6\xe2\x92\xb7\xe2\x92\xb8\xe2\x92\xb9"
    # This is the UTF-8 encoding of the string in the
    # previous example

    $foo = pack("ccxxcc",65,66,67,68);
    # foo eq "AB\0\0CD"

    # NOTE: The examples above featuring "W" and "c" are true
    # only on ASCII and ASCII-derived systems such as ISO Latin 1
    # and UTF-8.  On EBCDIC systems, the first example would be
    #      $foo = pack("WWWW",193,194,195,196);

    $foo = pack("s2",1,2);
    # "\001\000\002\000" on little-endian
    # "\000\001\000\002" on big-endian

    $foo = pack("a4","abcd","x","y","z");
    # "abcd"

    $foo = pack("aaaa","abcd","x","y","z");
    # "axyz"

    $foo = pack("a14","abcdefg");
    # "abcdefg\0\0\0\0\0\0\0"

    $foo = pack("i9pl", gmtime);
    # a real struct tm (on my system anyway)

    $utmp_template = "Z8 Z8 Z16 L";
    $utmp = pack($utmp_template, @utmp1);
    # a struct utmp (BSDish)

    @utmp2 = unpack($utmp_template, $utmp);
    # "@utmp1" eq "@utmp2"

    sub bintodec {
        unpack("N", pack("B32", substr("0" x 32 . shift, -32)));
    }

    $foo = pack('sx2l', 12, 34);
    # short 12, two zero bytes padding, long 34
    $bar = pack('s@4l', 12, 34);
    # short 12, zero fill to position 4, long 34
    # $foo eq $bar
    $baz = pack('s.l', 12, 4, 34);
    # short 12, zero fill to position 4, long 34

    $foo = pack('nN', 42, 4711);
    # pack big-endian 16- and 32-bit unsigned integers
    $foo = pack('S>L>', 42, 4711);
    # exactly the same
    $foo = pack('s<l<', -42, 4711);
    # pack little-endian 16- and 32-bit signed integers
    $foo = pack('(sl)<', -42, 4711);
    # exactly the same

The same template may generally also be used in unpack.

一般的には、同じテンプレートが unpack でも 使用できます。