オープンソース・ソフトウェアの開発とダウンロード

CVS リポジトリの参照

Annotation of /perldocjp/docs/perl/5.10.0/perlpacktut.pod

Parent Directory Parent Directory | Revision Log Revision Log | View Revision Graph Revision Graph


Revision 1.2 - (hide annotations) (download)
Sat Apr 30 19:17:47 2011 UTC (13 years ago) by argrath
Branch: MAIN
Changes since 1.1: +1 -1 lines
adjust meta data

1 argrath 1.1
2     =encoding euc-jp
3    
4     =head1 NAME
5    
6     =begin original
7    
8     perlpacktut - tutorial on C<pack> and C<unpack>
9    
10     =end original
11    
12     perlpacktut - C<pack> と C<unpack> のチュートリアル
13    
14     =head1 DESCRIPTION
15    
16     =begin original
17    
18     C<pack> and C<unpack> are two functions for transforming data according
19     to a user-defined template, between the guarded way Perl stores values
20     and some well-defined representation as might be required in the
21     environment of a Perl program. Unfortunately, they're also two of
22     the most misunderstood and most often overlooked functions that Perl
23     provides. This tutorial will demystify them for you.
24    
25     =end original
26    
27     C<pack> と C<unpack> は、ユーザーが定義したテンプレートに従って、
28     Perl が値を保管する保護された方法と、Perl プログラムの環境で必要になる
29     かもしれないよく定義された表現の間を変換する二つの関数です。
30     残念ながら、これらは Perl が提供する関数の中でもっとも誤解され、
31     もっとも見落とされやすい関数でもあります。
32     このチュートリアルではこれらを分かりやすく説明します。
33    
34     =head1 The Basic Principle
35    
36     (基本原理)
37    
38     =begin original
39    
40     Most programming languages don't shelter the memory where variables are
41     stored. In C, for instance, you can take the address of some variable,
42     and the C<sizeof> operator tells you how many bytes are allocated to
43     the variable. Using the address and the size, you may access the storage
44     to your heart's content.
45    
46     =end original
47    
48     多くのプログラミング言語は変数が格納されているメモリを保護していません。
49     例えば、C では、ある変数のアドレスを取得できますし、
50     C<sizeof> 演算子は変数に何バイト割り当てられているかを返します。
51     アドレスとサイズを使って、心臓部にあるストレージにアクセスできます。
52    
53     =begin original
54    
55     In Perl, you just can't access memory at random, but the structural and
56     representational conversion provided by C<pack> and C<unpack> is an
57     excellent alternative. The C<pack> function converts values to a byte
58     sequence containing representations according to a given specification,
59     the so-called "template" argument. C<unpack> is the reverse process,
60     deriving some values from the contents of a string of bytes. (Be cautioned,
61     however, that not all that has been packed together can be neatly unpacked -
62     a very common experience as seasoned travellers are likely to confirm.)
63    
64     =end original
65    
66     Perl では、メモリにランダムにアクセスすることはできませんが、C<pack> と
67     C<unpack> によって提供される構造的および表現的な変換は素晴らしい
68     代替案です。
69     C<pack> 関数は、値を、「テンプレート」引数と呼ばれる使用に従った表現を含む
70     バイト列に変換します。
71     C<unpack> は逆処理で、バイトの並びから値を引き出します。
72     (しかし、pack された全てのデータがうまく unpack できるというわけでは
73     ないということは注意してください - 経験豊かな旅人が確認しそうな、とても
74     一般的な経験です。)
75    
76     =begin original
77    
78     Why, you may ask, would you need a chunk of memory containing some values
79     in binary representation? One good reason is input and output accessing
80     some file, a device, or a network connection, whereby this binary
81     representation is either forced on you or will give you some benefit
82     in processing. Another cause is passing data to some system call that
83     is not available as a Perl function: C<syscall> requires you to provide
84     parameters stored in the way it happens in a C program. Even text processing
85     (as shown in the next section) may be simplified with judicious usage
86     of these two functions.
87    
88     =end original
89    
90     あなたはどうしてバイナリ表現の中に値が含まれているメモリの塊が
91     必要なのか、と問うかもしれません。
92     よい理由の一つは、ファイル、デバイス、ネットワーク接続にアクセスする
93     入出力で、このバイナリ表現が強制されたものか、処理するためにいくらかの
94     利益がある場合です。
95     もう一つの原因は、Perl 関数として利用できないシステムコールにデータを
96     渡すときです: C<syscall> は C プログラムでのような形で保管された引数を
97     提供することを要求します。
98     (以下の章で示すように) テキスト処理ですら、これら 2 つの関数を賢明に
99     使うことで単純化できます。
100    
101     =begin original
102    
103     To see how (un)packing works, we'll start with a simple template
104     code where the conversion is in low gear: between the contents of a byte
105     sequence and a string of hexadecimal digits. Let's use C<unpack>, since
106     this is likely to remind you of a dump program, or some desperate last
107     message unfortunate programs are wont to throw at you before they expire
108     into the wild blue yonder. Assuming that the variable C<$mem> holds a
109     sequence of bytes that we'd like to inspect without assuming anything
110     about its meaning, we can write
111    
112     =end original
113    
114     (un)pack がどのように働くのかを見るために、変換がのろのろと行われる単純な
115     テンプレートコードから始めましょう: バイトシーケンスと 16 進数の文字列との
116     変換です。
117     C<unpack> を使いましょう; なぜならこれはダンププログラムや、
118     不幸なプログラムが息を引き取る前にあなたに投げかけることが常となっている
119     絶望的な最後のメッセージを思い出させそうだからです。
120     変数 C<$mem> に、その意味について何の仮定もおかずに調査したいバイト列が
121     入っていると仮定すると、以下のように書きます:
122    
123     my( $hex ) = unpack( 'H*', $mem );
124     print "$hex\n";
125    
126     =begin original
127    
128     whereupon we might see something like this, with each pair of hex digits
129     corresponding to a byte:
130    
131     =end original
132    
133     するとすぐに、1 バイトに対応して 16 進数 2 文字が対応する、以下のような
134     ものが表示されます:
135    
136     41204d414e204120504c414e20412043414e414c2050414e414d41
137    
138     =begin original
139    
140     What was in this chunk of memory? Numbers, characters, or a mixture of
141     both? Assuming that we're on a computer where ASCII (or some similar)
142     encoding is used: hexadecimal values in the range C<0x40> - C<0x5A>
143     indicate an uppercase letter, and C<0x20> encodes a space. So we might
144     assume it is a piece of text, which some are able to read like a tabloid;
145     but others will have to get hold of an ASCII table and relive that
146     firstgrader feeling. Not caring too much about which way to read this,
147     we note that C<unpack> with the template code C<H> converts the contents
148     of a sequence of bytes into the customary hexadecimal notation. Since
149     "a sequence of" is a pretty vague indication of quantity, C<H> has been
150     defined to convert just a single hexadecimal digit unless it is followed
151     by a repeat count. An asterisk for the repeat count means to use whatever
152     remains.
153    
154     =end original
155    
156     このメモリの塊はなんでしょう?
157     数値、文字、あるいはそれらの混合でしょうか?
158     使っているコンピュータが ASCII エンコーディング (あるいは似たようなもの) を
159     使っていると仮定します: C<0x40> - C<0x5A> 範囲の 16 進数は大文字を
160     示していて、C<0x20> は空白をエンコードしたものです。
161     それで、これは、タブロイドのように読むことのできるテキストの断片と
162     仮定できます; その他は ASCII テーブルを持って 1 年生の感覚を思い出す
163     必要があります。
164     これをどのようにして読むかについてはあまり気にしないことにして、
165     we note that
166     C<unpack> のテンプレートコード C<H> はバイト列の内容をいつもの 16 進表記に
167     変換することに注目します。
168     「列」というのは量についてあいまいなので、
169     C<H> は、引き続いて繰り返し回数がない場合は単に 1 つの 16 進数を
170     変換するように定義されています。
171     繰り返し数でのアスタリスクは、残っているもの全てを使うことを意味します。
172    
173     =begin original
174    
175     The inverse operation - packing byte contents from a string of hexadecimal
176     digits - is just as easily written. For instance:
177    
178     =end original
179    
180     逆操作 - 16 進数の文字列からバイトの内容に pack する - は簡単に書けます。
181     例えば:
182    
183     my $s = pack( 'H2' x 10, map { "3$_" } ( 0..9 ) );
184     print "$s\n";
185    
186     =begin original
187    
188     Since we feed a list of ten 2-digit hexadecimal strings to C<pack>, the
189     pack template should contain ten pack codes. If this is run on a computer
190     with ASCII character coding, it will print C<0123456789>.
191    
192     =end original
193    
194     16 進で 2 桁の数値を示す文字列 10 個からなるリストを C<pack> に
195     渡しているので、pack テンプレートは 10 個の pack コードを含んでいる
196     必要があります。
197     これが ASCII 文字コードのコンピュータで実行されると、C<0123456789> を
198     表示します。
199    
200     =head1 Packing Text
201    
202     (テキストを pack する)
203    
204     =begin original
205    
206     Let's suppose you've got to read in a data file like this:
207    
208     =end original
209    
210     以下のようなデータファイルを読み込むことを考えます:
211    
212     Date |Description | Income|Expenditure
213     01/24/2001 Ahmed's Camel Emporium 1147.99
214     01/28/2001 Flea spray 24.99
215     01/29/2001 Camel rides to tourists 235.00
216    
217     =begin original
218    
219     How do we do it? You might think first to use C<split>; however, since
220     C<split> collapses blank fields, you'll never know whether a record was
221     income or expenditure. Oops. Well, you could always use C<substr>:
222    
223     =end original
224    
225     どうすればいいでしょう?
226     最初に思いつくのは C<split> かもしれません;
227     しかし、C<split> は空白のフィールドを壊してしまうので、
228     そのレコードが収入だったか支出だったが分かりません。あらら。
229     では、C<substr> を使うとどうでしょう:
230    
231     while (<>) {
232     my $date = substr($_, 0, 11);
233     my $desc = substr($_, 12, 27);
234     my $income = substr($_, 40, 7);
235     my $expend = substr($_, 52, 7);
236     ...
237     }
238    
239     =begin original
240    
241     It's not really a barrel of laughs, is it? In fact, it's worse than it
242     may seem; the eagle-eyed may notice that the first field should only be
243     10 characters wide, and the error has propagated right through the other
244     numbers - which we've had to count by hand. So it's error-prone as well
245     as horribly unfriendly.
246    
247     =end original
248    
249     これはあまり愉快ではないですよね?
250     実際、これは思ったより悪いです; 注意深い人は最初のフィールドが 10 文字分しか
251     なく、エラーが他の数値に拡大してしまう - 手で数えなければなりません -
252     ことに気付くでしょう。
253     従って、これは恐ろしく不親切であると同様、間違いが発生しやすいです.
254    
255     =begin original
256    
257     Or maybe we could use regular expressions:
258    
259     =end original
260    
261     あるいは正規表現も使えます:
262    
263     while (<>) {
264     my($date, $desc, $income, $expend) =
265     m|(\d\d/\d\d/\d{4}) (.{27}) (.{7})(.*)|;
266     ...
267     }
268    
269     =begin original
270    
271     Urgh. Well, it's a bit better, but - well, would you want to maintain
272     that?
273    
274     =end original
275    
276     うわあ。えーと、少しましです。
277     しかし - えーと、これを保守したいと思います?
278    
279     =begin original
280    
281     Hey, isn't Perl supposed to make this sort of thing easy? Well, it does,
282     if you use the right tools. C<pack> and C<unpack> are designed to help
283     you out when dealing with fixed-width data like the above. Let's have a
284     look at a solution with C<unpack>:
285    
286     =end original
287    
288     ねえ、Perl はこの手のことを簡単にできないの?
289     ええ、できます、正しい道具を使えば。
290     C<pack> と C<unpack> は上記のような固定長データを扱う時の
291     助けになるように設計されています。
292     C<unpack> による解法を見てみましょう:
293    
294     while (<>) {
295     my($date, $desc, $income, $expend) = unpack("A10xA27xA7A*", $_);
296     ...
297     }
298    
299     =begin original
300    
301     That looks a bit nicer; but we've got to take apart that weird template.
302     Where did I pull that out of?
303    
304     =end original
305    
306     これはちょっとましに見えます;
307     でも変なテンプレートを分析しなければなりません。
308     これはどこから来たのでしょう?
309    
310     =begin original
311    
312     OK, let's have a look at some of our data again; in fact, we'll include
313     the headers, and a handy ruler so we can keep track of where we are.
314    
315     =end original
316    
317     よろしい、ここでデータをもう一度見てみましょう;
318     実際、ヘッダも含めて、何をしているかを追いかけるために
319     手書きの目盛りも付けています。
320    
321     1 2 3 4 5
322     1234567890123456789012345678901234567890123456789012345678
323     Date |Description | Income|Expenditure
324     01/28/2001 Flea spray 24.99
325     01/29/2001 Camel rides to tourists 235.00
326    
327     =begin original
328    
329     From this, we can see that the date column stretches from column 1 to
330     column 10 - ten characters wide. The C<pack>-ese for "character" is
331     C<A>, and ten of them are C<A10>. So if we just wanted to extract the
332     dates, we could say this:
333    
334     =end original
335    
336     ここから、日付の桁は 1 桁目から 10 桁目まで - 10 文字の幅があることが
337     わかります。
338     「文字」のパックは C<A> で、10 文字の場合は C<A10> です。
339     それで、もし単に日付を展開したいだけなら、以下のように書けます:
340    
341     my($date) = unpack("A10", $_);
342    
343     =begin original
344    
345     OK, what's next? Between the date and the description is a blank column;
346     we want to skip over that. The C<x> template means "skip forward", so we
347     want one of those. Next, we have another batch of characters, from 12 to
348     38. That's 27 more characters, hence C<A27>. (Don't make the fencepost
349     error - there are 27 characters between 12 and 38, not 26. Count 'em!)
350    
351     =end original
352    
353     よろしい、次は?
354     日付と説明の間には空白の桁があります;これは読み飛ばしたいです。
355     C<x> テンプレートは「読み飛ばす」ことを意味し、
356     これで 1 文字読み飛ばせます。
357     次に、別の文字の塊が 12 桁から 38 桁まであります。
358     これは 27 文字あるので、C<A27> です。
359     (数え間違えないように - 12 から 38 の間には 26 ではなく 27 文字あります。)
360    
361     =begin original
362    
363     Now we skip another character and pick up the next 7 characters:
364    
365     =end original
366    
367     次の文字は読み飛ばして、次の 7 文字を取り出します:
368    
369     my($date,$description,$income) = unpack("A10xA27xA7", $_);
370    
371     =begin original
372    
373     Now comes the clever bit. Lines in our ledger which are just income and
374     not expenditure might end at column 46. Hence, we don't want to tell our
375     C<unpack> pattern that we B<need> to find another 12 characters; we'll
376     just say "if there's anything left, take it". As you might guess from
377     regular expressions, that's what the C<*> means: "use everything
378     remaining".
379    
380     =end original
381    
382     ここで少し賢くやりましょう。
383     台帳のうち、収入だけがあって支出がない行は 46 行目で終わっています。
384     従って、次の 12 文字を見つける B<必要がある> ということを
385     C<unpack> パターンに書きたくはありません;
386     単に次のようにします「もし何かが残っていれば、それを取ります」。
387     正規表現から推測したかもしれませんが、これが C<*> の意味することです:
388     「残っているもの全てを使います」。
389    
390     =over 3
391    
392     =item *
393    
394     =begin original
395    
396     Be warned, though, that unlike regular expressions, if the C<unpack>
397     template doesn't match the incoming data, Perl will scream and die.
398    
399     =end original
400    
401     但し、正規表現とは違うことに注意してください。
402     もし C<unpack> テンプレートが入力データと一致しない場合、
403     Perl は悲鳴をあげて die します。
404    
405     =back
406    
407     =begin original
408    
409     Hence, putting it all together:
410    
411     =end original
412    
413     従って、これを全部あわせると:
414    
415     my($date,$description,$income,$expend) = unpack("A10xA27xA7xA*", $_);
416    
417     =begin original
418    
419     Now, that's our data parsed. I suppose what we might want to do now is
420     total up our income and expenditure, and add another line to the end of
421     our ledger - in the same format - saying how much we've brought in and
422     how much we've spent:
423    
424     =end original
425    
426     これで、データがパースできます。
427     今ほしいものが収入と支出をそれぞれ足し合わせて、台帳の最後に - 同じ形式で -
428     1 行付け加えることで、どれだけの収入と支出があったかを記すことだとします:
429    
430     while (<>) {
431     my($date, $desc, $income, $expend) = unpack("A10xA27xA7xA*", $_);
432     $tot_income += $income;
433     $tot_expend += $expend;
434     }
435    
436     $tot_income = sprintf("%.2f", $tot_income); # Get them into
437     $tot_expend = sprintf("%.2f", $tot_expend); # "financial" format
438    
439     $date = POSIX::strftime("%m/%d/%Y", localtime);
440    
441     # OK, let's go:
442    
443     print pack("A10xA27xA7xA*", $date, "Totals", $tot_income, $tot_expend);
444    
445     =begin original
446    
447     Oh, hmm. That didn't quite work. Let's see what happened:
448    
449     =end original
450    
451     あら、ふうむ。
452     これはうまく動きません。
453     何が起こったのか見てみましょう:
454    
455     01/24/2001 Ahmed's Camel Emporium 1147.99
456     01/28/2001 Flea spray 24.99
457     01/29/2001 Camel rides to tourists 1235.00
458     03/23/2001Totals 1235.001172.98
459    
460     =begin original
461    
462     OK, it's a start, but what happened to the spaces? We put C<x>, didn't
463     we? Shouldn't it skip forward? Let's look at what L<perlfunc/pack> says:
464    
465     =end original
466    
467     まあ、これはスタートです; しかしスペースに何が起きたのでしょう?
468     C<x> を指定しましたよね?
469     これでは飛ばせない?
470     L<perlfunc/pack> に書いていることを見てみましょう:
471    
472     x A null byte.
473    
474     =begin original
475    
476     Urgh. No wonder. There's a big difference between "a null byte",
477     character zero, and "a space", character 32. Perl's put something
478     between the date and the description - but unfortunately, we can't see
479     it!
480    
481     =end original
482    
483     うはあ。
484     当たり前です。
485     文字コード 0 の「ヌル文字」と、文字コード 32 の「空白」は全然違います。
486     Perl は日付と説明の間に何かを書いたのです - しかし残念ながら、
487     それは見えません!
488    
489     =begin original
490    
491     What we actually need to do is expand the width of the fields. The C<A>
492     format pads any non-existent characters with spaces, so we can use the
493     additional spaces to line up our fields, like this:
494    
495     =end original
496    
497     実際に必要なことはフィールドの幅を増やすことです。
498     C<A> フォーマットは存在しない文字を空白でパッディングするので、
499     以下のようにフィールドに空白の分だけ桁数を増やします:
500    
501     print pack("A11 A28 A8 A*", $date, "Totals", $tot_income, $tot_expend);
502    
503     =begin original
504    
505     (Note that you can put spaces in the template to make it more readable,
506     but they don't translate to spaces in the output.) Here's what we got
507     this time:
508    
509     =end original
510    
511     (テンプレートには読みやすくするために空白を入れることができますが、
512     出力には反映されないことに注意してください。)
513     これで得られたのは以下のものです:
514    
515     01/24/2001 Ahmed's Camel Emporium 1147.99
516     01/28/2001 Flea spray 24.99
517     01/29/2001 Camel rides to tourists 1235.00
518     03/23/2001 Totals 1235.00 1172.98
519    
520     =begin original
521    
522     That's a bit better, but we still have that last column which needs to
523     be moved further over. There's an easy way to fix this up:
524     unfortunately, we can't get C<pack> to right-justify our fields, but we
525     can get C<sprintf> to do it:
526    
527     =end original
528    
529     これで少し良くなりましたが、まだ、最後の桁をもっと向こうに移動させる
530     必要があります。
531     これを修正する簡単な方法があります:
532     残念ながら C<pack> でフィールドを右寄せにすることは出来ませんが、
533     C<sprintf> を使えば出来ます:
534    
535     $tot_income = sprintf("%.2f", $tot_income);
536     $tot_expend = sprintf("%12.2f", $tot_expend);
537     $date = POSIX::strftime("%m/%d/%Y", localtime);
538     print pack("A11 A28 A8 A*", $date, "Totals", $tot_income, $tot_expend);
539    
540     =begin original
541    
542     This time we get the right answer:
543    
544     =end original
545    
546     今度は正しい答えを得られました:
547    
548     01/28/2001 Flea spray 24.99
549     01/29/2001 Camel rides to tourists 1235.00
550     03/23/2001 Totals 1235.00 1172.98
551    
552     =begin original
553    
554     So that's how we consume and produce fixed-width data. Let's recap what
555     we've seen of C<pack> and C<unpack> so far:
556    
557     =end original
558    
559     ということで、これが固定長データを読み書きする方法です。
560     ここまでで C<pack> と C<unpack> について見たことを復習しましょう:
561    
562     =over 3
563    
564     =item *
565    
566     =begin original
567    
568     Use C<pack> to go from several pieces of data to one fixed-width
569     version; use C<unpack> to turn a fixed-width-format string into several
570     pieces of data.
571    
572     =end original
573    
574     複数のデータ片を一つの固定長データにするには C<pack> を使います;
575     固定長フォーマット文字列を複数のデータ片にするには C<unpack> を使います。
576    
577     =item *
578    
579     =begin original
580    
581     The pack format C<A> means "any character"; if you're C<pack>ing and
582     you've run out of things to pack, C<pack> will fill the rest up with
583     spaces.
584    
585     =end original
586    
587     pack フォーマット C<A> は「任意の文字」を意味します; もし C<pack> 中に
588     pack するものがなくなったら、C<pack> は残りを空白で埋めます。
589    
590     =item *
591    
592     =begin original
593    
594     C<x> means "skip a byte" when C<unpack>ing; when C<pack>ing, it means
595     "introduce a null byte" - that's probably not what you mean if you're
596     dealing with plain text.
597    
598     =end original
599    
600     C<unpack> での C<x> は「1 バイト読み飛ばす」ことを意味します;
601     C<pack> では、「ヌルバイトを生成する」ことを意味します -
602     これは、プレーンテキストを扱っている場合はおそらく望んでいるものでは
603     ないでしょう。
604    
605     =item *
606    
607     =begin original
608    
609     You can follow the formats with numbers to say how many characters
610     should be affected by that format: C<A12> means "take 12 characters";
611     C<x6> means "skip 6 bytes" or "character 0, 6 times".
612    
613     =end original
614    
615     フォーマットの後に数値をつけることで、フォーマットに影響される文字数を
616     指定します: C<A12> は「12 文字取る」ことを意味します;
617     C<x6> は「6 バイト読み飛ばす」や「ヌルバイト 6 つ」を意味します。
618    
619     =item *
620    
621     =begin original
622    
623     Instead of a number, you can use C<*> to mean "consume everything else
624     left".
625    
626     =end original
627    
628     数値の代わりに、C<*> で「残っているもの全てを使う」ことを指定できます。
629    
630     =begin original
631    
632     B<Warning>: when packing multiple pieces of data, C<*> only means
633     "consume all of the current piece of data". That's to say
634    
635     =end original
636    
637     B<警告>: 複数のデータ片を pack するとき、C<*> は「現在のデータ片を全て
638     含む」という意味だけです。
639     これは、以下のようにすると:
640    
641     pack("A*A*", $one, $two)
642    
643     =begin original
644    
645     packs all of C<$one> into the first C<A*> and then all of C<$two> into
646     the second. This is a general principle: each format character
647     corresponds to one piece of data to be C<pack>ed.
648    
649     =end original
650    
651     C<$one> の全てを最初の C<A*> に pack し、それから C<$two> の全てを二番目に
652     pack します。
653     ここに一般的な原則があります: 各フォーマット文字は C<pack> されるデータ片
654     一つに対応します。
655    
656     =back
657    
658     =head1 Packing Numbers
659    
660     (数値を pack する)
661    
662     =begin original
663    
664     So much for textual data. Let's get onto the meaty stuff that C<pack>
665     and C<unpack> are best at: handling binary formats for numbers. There is,
666     of course, not just one binary format - life would be too simple - but
667     Perl will do all the finicky labor for you.
668    
669     =end original
670    
671     テキストデータについてはこれくらいです。
672     C<pack> と C<unpack> が最良である、いやらしい代物: 数値のためのバイナリ
673     フォーマットに進みましょう。
674     もちろん、バイナリフォーマットはひとつではありません - 人生はそれほど
675     単純ではありません - が、Perl は全ての細かい作業を行います。
676    
677     =head2 Integers
678    
679     (整数)
680    
681     =begin original
682    
683     Packing and unpacking numbers implies conversion to and from some
684     I<specific> binary representation. Leaving floating point numbers
685     aside for the moment, the salient properties of any such representation
686     are:
687    
688     =end original
689    
690     数値を pack や unpack するということは、I<特定の> バイナリ表現との間で
691     変換するということを意味します。
692     今のところ浮動小数点数は脇にやっておくとすると、このような表現の
693     主要な性質としては:
694    
695     =over 4
696    
697     =item *
698    
699     =begin original
700    
701     the number of bytes used for storing the integer,
702    
703     =end original
704    
705     整数の保存に使うバイト数。
706    
707     =item *
708    
709     =begin original
710    
711     whether the contents are interpreted as a signed or unsigned number,
712    
713     =end original
714    
715     内容を符号なし数として解釈するか符号付き数として解釈するか。
716    
717     =item *
718    
719     =begin original
720    
721     the byte ordering: whether the first byte is the least or most
722     significant byte (or: little-endian or big-endian, respectively).
723    
724     =end original
725    
726     バイト順序:最初のバイトは最下位バイトか最上位バイトか
727     (言い換えると: それぞれリトルエンディアンかビッグエンディアンか)。
728    
729     =back
730    
731     =begin original
732    
733     So, for instance, to pack 20302 to a signed 16 bit integer in your
734     computer's representation you write
735    
736     =end original
737    
738     それで、例えば、20302 をあなたのコンピュータの符号付き 16 ビット整数に
739     pack するとすると、以下のように書きます:
740    
741     my $ps = pack( 's', 20302 );
742    
743     =begin original
744    
745     Again, the result is a string, now containing 2 bytes. If you print
746     this string (which is, generally, not recommended) you might see
747     C<ON> or C<NO> (depending on your system's byte ordering) - or something
748     entirely different if your computer doesn't use ASCII character encoding.
749     Unpacking C<$ps> with the same template returns the original integer value:
750    
751     =end original
752    
753     再び、結果は 2 バイトからなる文字列です。
754     もしこの文字列を表示する(これは一般的にはお勧めできません)と、
755     C<ON> か C<NO> (システムのバイト順に依存します) - または、もし
756     コンピューターが ASCII 文字エンコーディングを使っていないなら全く違う
757     文字列が表示されます。
758     C<$ps> を同じテンプレートで unpack すると、元の整数値が返ります:
759    
760     my( $s ) = unpack( 's', $ps );
761    
762     =begin original
763    
764     This is true for all numeric template codes. But don't expect miracles:
765     if the packed value exceeds the allotted byte capacity, high order bits
766     are silently discarded, and unpack certainly won't be able to pull them
767     back out of some magic hat. And, when you pack using a signed template
768     code such as C<s>, an excess value may result in the sign bit
769     getting set, and unpacking this will smartly return a negative value.
770    
771     =end original
772    
773     これは全ての数値テンプレートコードに対して真です。
774     しかし奇跡を期待してはいけません:
775     もし pack された値が割り当てられたバイト容量を超えると、高位ビットは
776     黙って捨てられ、unpack は確実に魔法の帽子からデータを
777     取り出すことができません。
778     そして、C<s> のような符号付きテンプレートコードを使って pack すると、
779     超えた値が符号ビットをセットすることになり、unpack すると負の値が
780     返されることになるかもしれません。
781    
782     =begin original
783    
784     16 bits won't get you too far with integers, but there is C<l> and C<L>
785     for signed and unsigned 32-bit integers. And if this is not enough and
786     your system supports 64 bit integers you can push the limits much closer
787     to infinity with pack codes C<q> and C<Q>. A notable exception is provided
788     by pack codes C<i> and C<I> for signed and unsigned integers of the
789     "local custom" variety: Such an integer will take up as many bytes as
790     a local C compiler returns for C<sizeof(int)>, but it'll use I<at least>
791     32 bits.
792    
793     =end original
794    
795     16 ビットは整数に十分とは言えませんが、符号付きと符号なしの 32 ビット
796     整数のための C<l> と C<L> もあります。
797     そして、これで十分ではなく、システムが 64 ビット整数に対応しているなら、
798     pack コード C<q> と C<Q> を使って限界をほぼ無限にまで押しやることができます。
799     注目すべき例外は pack コード C<i> と C<I> で、「ローカルに特化した」
800     符号付きと符号なしの整数を提供します: このような整数は C<sizeof(int)> と
801     したときにローカルな C コンパイラが返す値と同じバイト数ですが、
802     I<少なくとも> 32 ビットを使います。
803    
804     =begin original
805    
806     Each of the integer pack codes C<sSlLqQ> results in a fixed number of bytes,
807     no matter where you execute your program. This may be useful for some
808     applications, but it does not provide for a portable way to pass data
809     structures between Perl and C programs (bound to happen when you call
810     XS extensions or the Perl function C<syscall>), or when you read or
811     write binary files. What you'll need in this case are template codes that
812     depend on what your local C compiler compiles when you code C<short> or
813     C<unsigned long>, for instance. These codes and their corresponding
814     byte lengths are shown in the table below. Since the C standard leaves
815     much leeway with respect to the relative sizes of these data types, actual
816     values may vary, and that's why the values are given as expressions in
817     C and Perl. (If you'd like to use values from C<%Config> in your program
818     you have to import it with C<use Config>.)
819    
820     =end original
821    
822     整数 pack コード C<sSlLqQ> のそれぞれは、どこでプログラムが
823     実行されたとしても固定長のバイト列となります。
824     これは一部のアプリケーションでは有用ですが、(XS エクステンションや
825     Perl 関数 C<syscall> を呼び出すときに必要となる)
826     Perl と C のプログラムの間でデータ構造を渡す場合や、バイナリファイルを
827     読み書きするときの、移植性のある手段は提供しません
828     この場合に必要なものは、例えば、C<short> や C<unsigned long> と書いたときに
829     ローカルの C コンパイラがどのようにコンパイルするかに依存する
830     テンプレートコードです。
831     これらのコードと、それに対応するバイト長は以下のテーブルの様になります。
832     C 標準はそれぞれのデータ型の大きさの点で多くの自由裁量を残しているので、
833     実際の値は異なるかもしれず、そしてこれがなぜ値が C と Perl の式として
834     与えられているかの理由です。
835     (もしプログラムで C<%Config> の値を使いたい場合は、C<use Config> として
836     これをインポートする必要があります。)
837    
838     =begin original
839    
840     signed unsigned byte length in C byte length in Perl
841     s! S! sizeof(short) $Config{shortsize}
842     i! I! sizeof(int) $Config{intsize}
843     l! L! sizeof(long) $Config{longsize}
844     q! Q! sizeof(long long) $Config{longlongsize}
845    
846     =end original
847    
848     符号付き 符号なし C でのバイト長 Perl でのバイト長
849     s! S! sizeof(short) $Config{shortsize}
850     i! I! sizeof(int) $Config{intsize}
851     l! L! sizeof(long) $Config{longsize}
852     q! Q! sizeof(long long) $Config{longlongsize}
853    
854     =begin original
855    
856     The C<i!> and C<I!> codes aren't different from C<i> and C<I>; they are
857     tolerated for completeness' sake.
858    
859     =end original
860    
861     C<i!> および C<I!> は C<i> および C<I> と違いはありません; これらは
862     完全性のために許容されています。
863    
864     =head2 Unpacking a Stack Frame
865    
866     (スタックフレームを unpack する)
867    
868     =begin original
869    
870     Requesting a particular byte ordering may be necessary when you work with
871     binary data coming from some specific architecture whereas your program could
872     run on a totally different system. As an example, assume you have 24 bytes
873     containing a stack frame as it happens on an Intel 8086:
874    
875     =end original
876    
877     特定のアーキテクチャから来たバイナリに対して作業をする一方、プログラムが
878     全く違うシステムで動いている場合、特定のバイト順序の要求が必要になります。
879     例として、Intel 8086 のスタックフレームを含む 24 バイトを仮定します:
880    
881     +---------+ +----+----+ +---------+
882     TOS: | IP | TOS+4:| FL | FH | FLAGS TOS+14:| SI |
883     +---------+ +----+----+ +---------+
884     | CS | | AL | AH | AX | DI |
885     +---------+ +----+----+ +---------+
886     | BL | BH | BX | BP |
887     +----+----+ +---------+
888     | CL | CH | CX | DS |
889     +----+----+ +---------+
890     | DL | DH | DX | ES |
891     +----+----+ +---------+
892    
893     =begin original
894    
895     First, we note that this time-honored 16-bit CPU uses little-endian order,
896     and that's why the low order byte is stored at the lower address. To
897     unpack such a (unsigned) short we'll have to use code C<v>. A repeat
898     count unpacks all 12 shorts:
899    
900     =end original
901    
902     まず、この伝統のある 16 ビット CPU はリトルエンディアンを使っていて、
903     それが低位バイトが低位アドレスに格納されている理由であることに
904     注意します。
905     このような(符号付き)short を unpack するには、コード C<v> を使う必要が
906     あるでしょう。
907     繰り返し数によって、12 全ての short を unpack します。
908    
909     my( $ip, $cs, $flags, $ax, $bx, $cd, $dx, $si, $di, $bp, $ds, $es ) =
910     unpack( 'v12', $frame );
911    
912     =begin original
913    
914     Alternatively, we could have used C<C> to unpack the individually
915     accessible byte registers FL, FH, AL, AH, etc.:
916    
917     =end original
918    
919     あるいは、FL, FH, AL, AH といったバイトレジスタに個々にアクセスできるように
920     unpack するための C<C> もあります:
921    
922     my( $fl, $fh, $al, $ah, $bl, $bh, $cl, $ch, $dl, $dh ) =
923     unpack( 'C10', substr( $frame, 4, 10 ) );
924    
925     =begin original
926    
927     It would be nice if we could do this in one fell swoop: unpack a short,
928     back up a little, and then unpack 2 bytes. Since Perl I<is> nice, it
929     proffers the template code C<X> to back up one byte. Putting this all
930     together, we may now write:
931    
932     =end original
933    
934     これを 1 回で行えたら素敵でしょう: short を unpack して、少し戻って、
935     それから 2 バイト unpack します。
936     Perl は I<素敵> なので、1 バイト戻るテンプレートコード C<X> を
937     提供しています。
938     これら全てを一緒にすると、以下のように書けます:
939    
940     my( $ip, $cs,
941     $flags,$fl,$fh,
942     $ax,$al,$ah, $bx,$bl,$bh, $cx,$cl,$ch, $dx,$dl,$dh,
943     $si, $di, $bp, $ds, $es ) =
944     unpack( 'v2' . ('vXXCC' x 5) . 'v5', $frame );
945    
946     =begin original
947    
948     (The clumsy construction of the template can be avoided - just read on!)
949    
950     =end original
951    
952     (この不細工なテンプレート構造は避けられます - 読み進めてください!)
953    
954     =begin original
955    
956     We've taken some pains to construct the template so that it matches
957     the contents of our frame buffer. Otherwise we'd either get undefined values,
958     or C<unpack> could not unpack all. If C<pack> runs out of items, it will
959     supply null strings (which are coerced into zeroes whenever the pack code
960     says so).
961    
962     =end original
963    
964     テンプレートを構築するのに少し苦労したのは、フレームバッファの内容に
965     一致させるためです。
966     さもなければ未定義値を受け取ることになるか、あるいは
967     C<unpack> は何も unpack できなくなります。
968     もし C<pack> で要素がなくなったら、空文字列を補います
969     (pack コードがそうするように言っていれば、ゼロに強制されます)。
970    
971     =head2 How to Eat an Egg on a Net
972    
973     (インターネットの卵の食べ方)
974    
975     =begin original
976    
977     The pack code for big-endian (high order byte at the lowest address) is
978     C<n> for 16 bit and C<N> for 32 bit integers. You use these codes
979     if you know that your data comes from a compliant architecture, but,
980     surprisingly enough, you should also use these pack codes if you
981     exchange binary data, across the network, with some system that you
982     know next to nothing about. The simple reason is that this
983     order has been chosen as the I<network order>, and all standard-fearing
984     programs ought to follow this convention. (This is, of course, a stern
985     backing for one of the Lilliputian parties and may well influence the
986     political development there.) So, if the protocol expects you to send
987     a message by sending the length first, followed by just so many bytes,
988     you could write:
989    
990     =end original
991    
992     ビッグエンディアン(最下位アドレスが最上位バイト)での pack コードは、
993     16 ビット整数が C<n>、 32 ビット整数が C<N> です。
994     もし準拠したアーキテクチャからデータが来ることが分かっているなら
995     これらのコードを使います;
996     もしネットワークを通して何も知らない他のシステムとバイナリデータを
997     交換する場合にもこれらの pack コードを使うべきです。
998     理由は単純で、この順序が I<ネットワーク順序> として選ばれていて、標準を
999     恐れる全てのプログラムがこの慣例に従っているはずだからです。
1000     (これはもちろん小人族の一行の一人の厳しい支援で、政治的な発展に
1001     影響を与えています。)
1002     それで、もし何バイトあるかの長さを先に送ることでメッセージを送ることを
1003     プロトコルが想定しているなら、以下のように書けます:
1004    
1005     my $buf = pack( 'N', length( $msg ) ) . $msg;
1006    
1007     =begin original
1008    
1009     or even:
1010    
1011     =end original
1012    
1013     あるいは:
1014    
1015     my $buf = pack( 'NA*', length( $msg ), $msg );
1016    
1017     =begin original
1018    
1019     and pass C<$buf> to your send routine. Some protocols demand that the
1020     count should include the length of the count itself: then just add 4
1021     to the data length. (But make sure to read L<"Lengths and Widths"> before
1022     you really code this!)
1023    
1024     =end original
1025    
1026     そして C<$buf> を送信ルーチンに渡します。
1027     カウントに、カウント自身の長さも含むことを要求しているプロトコルも
1028     あります: その時は単にデータ長に 4 を足してください。
1029     (しかし、実際にこれをコーディングする前に L<"Lengths and Widths"> を
1030     読んでください!)
1031    
1032     =head2 Byte-order modifiers
1033    
1034     (バイト順修飾子)
1035    
1036     =begin original
1037    
1038     In the previous sections we've learned how to use C<n>, C<N>, C<v> and
1039     C<V> to pack and unpack integers with big- or little-endian byte-order.
1040     While this is nice, it's still rather limited because it leaves out all
1041     kinds of signed integers as well as 64-bit integers. For example, if you
1042     wanted to unpack a sequence of signed big-endian 16-bit integers in a
1043     platform-independent way, you would have to write:
1044    
1045     =end original
1046    
1047     以前の章で、ビッグエンディアンとリトルエンディアンのバイト順の整数を
1048     pack および unpack するための C<n>, C<N>, C<v>, C<V> の使い方を学びました。
1049     これは素敵ですが、全ての種類の符号付き整数や、64 ビット整数が
1050     外れているので、まだいくらか制限されたものです。
1051     例えば、ビッグエンディアンの符号付き整数の並びをプラットフォームに
1052     依存しない方法で unpack したいとすると、以下のように書かなければなりません:
1053    
1054     my @data = unpack 's*', pack 'S*', unpack 'n*', $buf;
1055    
1056     =begin original
1057    
1058     This is ugly. As of Perl 5.9.2, there's a much nicer way to express your
1059     desire for a certain byte-order: the C<E<gt>> and C<E<lt>> modifiers.
1060     C<E<gt>> is the big-endian modifier, while C<E<lt>> is the little-endian
1061     modifier. Using them, we could rewrite the above code as:
1062    
1063     =end original
1064    
1065     これは醜いです。
1066     Perl 5.9.2 から、バイト順に関して望み通りに記述するための、遥かに
1067     素敵な方法があります: C<E<gt>> と C<E<lt>> の修飾子です。
1068     C<E<gt>> はビッグエンディアン修飾子で、C<E<lt>> は
1069     リトルエンディアン修飾子です。
1070     これらを使うと、上述のコードは以下のように書き換えられます:
1071    
1072     my @data = unpack 's>*', $buf;
1073    
1074     =begin original
1075    
1076     As you can see, the "big end" of the arrow touches the C<s>, which is a
1077     nice way to remember that C<E<gt>> is the big-endian modifier. The same
1078     obviously works for C<E<lt>>, where the "little end" touches the code.
1079    
1080     =end original
1081    
1082     見た通り、不等号の「大きい側」が C<s> に向いていて、C<E<gt>> が
1083     ビッグエンディアン修飾子であることを覚える素敵な方法となっています。
1084     明らかに同じことが、「小さい側」がコードに向いている C<E<lt>> にも働きます。
1085    
1086     =begin original
1087    
1088     You will probably find these modifiers even more useful if you have
1089     to deal with big- or little-endian C structures. Be sure to read
1090     L<"Packing and Unpacking C Structures"> for more on that.
1091    
1092     =end original
1093    
1094     おそらく、これらの修飾子はビッグエンディアンやリトルエンディアンの C 構造体を
1095     扱うときにもっと便利であることに気付くでしょう。
1096     これに関する詳細は、L<"Packing and Unpacking C Structures"> を
1097     よく読んでください。
1098    
1099     =head2 Floating point Numbers
1100    
1101     (浮動小数点数)
1102    
1103     =begin original
1104    
1105     For packing floating point numbers you have the choice between the
1106     pack codes C<f>, C<d>, C<F> and C<D>. C<f> and C<d> pack into (or unpack
1107     from) single-precision or double-precision representation as it is provided
1108     by your system. If your systems supports it, C<D> can be used to pack and
1109     unpack extended-precision floating point values (C<long double>), which
1110     can offer even more resolution than C<f> or C<d>. C<F> packs an C<NV>,
1111     which is the floating point type used by Perl internally. (There
1112     is no such thing as a network representation for reals, so if you want
1113     to send your real numbers across computer boundaries, you'd better stick
1114     to ASCII representation, unless you're absolutely sure what's on the other
1115     end of the line. For the even more adventuresome, you can use the byte-order
1116     modifiers from the previous section also on floating point codes.)
1117    
1118     =end original
1119    
1120     浮動小数点数を pack するには、pack コード C<f>, C<d>, C<F>, C<D> の
1121     選択肢があります。
1122     C<f> と C<d> pack はシステムで提供されている単精度と倍精度の実数に
1123     pack (あるいは unpack) します。
1124     もしシステムが対応していれば、C<f> や C<d> より精度のある、
1125     拡張精度浮動小数点数 (C<long double>) の pack および unpack のために
1126     C<D> が使えます。
1127     C<F> は、Perl が内部で使用している浮動小数点型である C<NV> を pack します。
1128     (実数に対してはネットワーク表現のようなものはないので、もし他の
1129     コンピュータに実数を送りたい場合は、ネットワークの向こう側で何が起きるかが
1130     完全に分かっているのでない限りは、ASCII 表現で我慢した方がよいです。
1131     より冒険的な場合でも、以前の章で触れたバイト順修飾子を浮動小数点コードにも
1132     使えます。)
1133    
1134     =head1 Exotic Templates
1135    
1136     (風変わりなテンプレート)
1137    
1138     =head2 Bit Strings
1139    
1140     (ビット文字列)
1141    
1142     =begin original
1143    
1144     Bits are the atoms in the memory world. Access to individual bits may
1145     have to be used either as a last resort or because it is the most
1146     convenient way to handle your data. Bit string (un)packing converts
1147     between strings containing a series of C<0> and C<1> characters and
1148     a sequence of bytes each containing a group of 8 bits. This is almost
1149     as simple as it sounds, except that there are two ways the contents of
1150     a byte may be written as a bit string. Let's have a look at an annotated
1151     byte:
1152    
1153     =end original
1154    
1155     ビットはメモリの世界の原子です。
1156     個々のビットへのアクセスは、最後の手段として行われるか、それがデータを
1157     扱うのに最も便利な方法であるときに行われます。
1158     (un)pack したビット文字列は、C<0> と C<1> の文字からなる文字列と、
1159     それぞれ 8 ビットを含むバイト列とを変換します。
1160     バイトの内容をビット文字列として書くには 2 つの方法があるということを除けば、
1161     これはほとんど見たままの単純さです。
1162     以下の注釈付きのバイトを見てみましょう:
1163    
1164     7 6 5 4 3 2 1 0
1165     +-----------------+
1166     | 1 0 0 0 1 1 0 0 |
1167     +-----------------+
1168     MSB LSB
1169    
1170     =begin original
1171    
1172     It's egg-eating all over again: Some think that as a bit string this should
1173     be written "10001100" i.e. beginning with the most significant bit, others
1174     insist on "00110001". Well, Perl isn't biased, so that's why we have two bit
1175     string codes:
1176    
1177     =end original
1178    
1179     卵の食べ方の繰り返しです: これは "10001100" というビット文字列になるべき、
1180     つまり最上位ビットから始めるべき、と考える人もいますし、
1181     "00110001" と主張する人もいます。
1182     ええ、Perl は偏向していないので、これが 2 つのビット文字列コードがある
1183     理由です:
1184    
1185     $byte = pack( 'B8', '10001100' ); # start with MSB
1186     $byte = pack( 'b8', '00110001' ); # start with LSB
1187    
1188     =begin original
1189    
1190     It is not possible to pack or unpack bit fields - just integral bytes.
1191     C<pack> always starts at the next byte boundary and "rounds up" to the
1192     next multiple of 8 by adding zero bits as required. (If you do want bit
1193     fields, there is L<perlfunc/vec>. Or you could implement bit field
1194     handling at the character string level, using split, substr, and
1195     concatenation on unpacked bit strings.)
1196    
1197     =end original
1198    
1199     ビットフィールドを pack や unpack することはできません -
1200     バイト単位だけです。
1201     C<pack> は常に次のバイト境界から始まり、必要な場合は 0 のビットを
1202     追加することで 8 の倍数に「切り上げ」られます。
1203     (もしビットフィールがほしいなら、L<perlfunc/vec> があります。
1204     あるいは、split, substr および unpack したビット文字列の結合を使って
1205     文字単位のレベルでビットフィールド操作を実装することも出来ます。)
1206    
1207     =begin original
1208    
1209     To illustrate unpacking for bit strings, we'll decompose a simple
1210     status register (a "-" stands for a "reserved" bit):
1211    
1212     =end original
1213    
1214     ビット文字列の unpack を図示するために、単純な状態レジスタを分解してみます
1215     ("-" は「予約された」ビットを意味します):
1216    
1217     +-----------------+-----------------+
1218     | S Z - A - P - C | - - - - O D I T |
1219     +-----------------+-----------------+
1220     MSB LSB MSB LSB
1221    
1222     =begin original
1223    
1224     Converting these two bytes to a string can be done with the unpack
1225     template C<'b16'>. To obtain the individual bit values from the bit
1226     string we use C<split> with the "empty" separator pattern which dissects
1227     into individual characters. Bit values from the "reserved" positions are
1228     simply assigned to C<undef>, a convenient notation for "I don't care where
1229     this goes".
1230    
1231     =end original
1232    
1233     これら 2 バイトから文字列への変換は unpack テンプレート C<'b16'> によって
1234     行われます。
1235     ビット文字列から個々のビット値を得るには、C<split> を「空」セパレータで
1236     使うことで個々の文字に切り刻みます。
1237     「予約された」位置からのビット値は単に C<undef> に代入しておきます;
1238     これは「この値がどこに行こうが気にしない」ことを示す便利な記法です。
1239    
1240     ($carry, undef, $parity, undef, $auxcarry, undef, $zero, $sign,
1241     $trace, $interrupt, $direction, $overflow) =
1242     split( //, unpack( 'b16', $status ) );
1243    
1244     =begin original
1245    
1246     We could have used an unpack template C<'b12'> just as well, since the
1247     last 4 bits can be ignored anyway.
1248    
1249     =end original
1250    
1251     ちょうど同じように、unpack テンプレート C<'b12'> も使えます;
1252     最後の 4 ビットはどちらにしろ無視されるからです。
1253    
1254     =head2 Uuencoding
1255    
1256     (uuencode)
1257    
1258     =begin original
1259    
1260     Another odd-man-out in the template alphabet is C<u>, which packs an
1261     "uuencoded string". ("uu" is short for Unix-to-Unix.) Chances are that
1262     you won't ever need this encoding technique which was invented to overcome
1263     the shortcomings of old-fashioned transmission mediums that do not support
1264     other than simple ASCII data. The essential recipe is simple: Take three
1265     bytes, or 24 bits. Split them into 4 six-packs, adding a space (0x20) to
1266     each. Repeat until all of the data is blended. Fold groups of 4 bytes into
1267     lines no longer than 60 and garnish them in front with the original byte count
1268     (incremented by 0x20) and a C<"\n"> at the end. - The C<pack> chef will
1269     prepare this for you, a la minute, when you select pack code C<u> on the menu:
1270    
1271     =end original
1272    
1273     テンプレートの中のもう一つの半端者は C<u> で、「uuencode された文字列」を
1274     pack します。
1275     ("uu" は Unix-to-Unix を縮めたものです。)
1276     あなたには、単純な ASCII データしか対応していない旧式の通信メディアの欠点を
1277     克服するために開発されたこのエンコーディング技術が必要になる機会は
1278     なかったかもしれません。
1279     本質的なレシピは単純です: 3 バイト、または 24 ビットを取ります。
1280     これを 4 つの 6 ビットに分け、それぞれに空白 (0x20) を加えます。
1281     全てのデータが混ぜられるまで繰り返します。
1282     4 バイトの組を 60 文字を超えない行に折り畳み、元のバイト数(0x20 を
1283     加えたもの)を先頭に置いて、末尾に C<"\n"> を置きます。
1284     - あなたがメニューから pack コード C<u> を選ぶと、C<pack> シェフは
1285     即席で、下ごしらえをしてくれます:
1286    
1287     my $uubuf = pack( 'u', $bindat );
1288    
1289     =begin original
1290    
1291     A repeat count after C<u> sets the number of bytes to put into an
1292     uuencoded line, which is the maximum of 45 by default, but could be
1293     set to some (smaller) integer multiple of three. C<unpack> simply ignores
1294     the repeat count.
1295    
1296     =end original
1297    
1298     C<u> の後の繰り返し数は uuencode された行にいれるバイト数で、デフォルトでは
1299     最大の 45 ですが、3 の倍数のその他の(より小さい)数にできます。
1300     C<unpack> は単に繰り返し数を無視します。
1301    
1302     =head2 Doing Sums
1303    
1304     (合計を計算する)
1305    
1306     =begin original
1307    
1308     An even stranger template code is C<%>E<lt>I<number>E<gt>. First, because
1309     it's used as a prefix to some other template code. Second, because it
1310     cannot be used in C<pack> at all, and third, in C<unpack>, doesn't return the
1311     data as defined by the template code it precedes. Instead it'll give you an
1312     integer of I<number> bits that is computed from the data value by
1313     doing sums. For numeric unpack codes, no big feat is achieved:
1314    
1315     =end original
1316    
1317     さらに不思議なテンプレートコードは C<%>E<lt>I<number>E<gt> です。
1318     第一に、これはその他のテンプレートコードの前置詞として使われるからです。
1319     第二に、C<pack> では全く使えず、第三に、C<unpack> では、先行する
1320     テンプレートコードによって定義された値を返さないからです。
1321     代わりに、これはデータの合計として計算された I<number> ビットの整数を
1322     与えます。
1323     数値 unpack コードでは、大きな離れ業は行われません:
1324    
1325     my $buf = pack( 'iii', 100, 20, 3 );
1326     print unpack( '%32i3', $buf ), "\n"; # prints 123
1327    
1328     =begin original
1329    
1330     For string values, C<%> returns the sum of the byte values saving
1331     you the trouble of a sum loop with C<substr> and C<ord>:
1332    
1333     =end original
1334    
1335     文字列値に対しては、C<%> はバイト値の合計を返し、C<substr> と C<ord> による
1336     合計計算ループによる問題からあなたを救います:
1337    
1338     print unpack( '%32A*', "\x01\x10" ), "\n"; # prints 17
1339    
1340     =begin original
1341    
1342     Although the C<%> code is documented as returning a "checksum":
1343     don't put your trust in such values! Even when applied to a small number
1344     of bytes, they won't guarantee a noticeable Hamming distance.
1345    
1346     =end original
1347    
1348     C<%> コードは「チェックサム」を返すと文書化されていますが:
1349     このような値に信頼を置いてはいけません!
1350     少量のバイト列に適用する場合ですら、顕著なハミング距離を保証できません。
1351    
1352     =begin original
1353    
1354     In connection with C<b> or C<B>, C<%> simply adds bits, and this can be put
1355     to good use to count set bits efficiently:
1356    
1357     =end original
1358    
1359     C<b> や C<B> と共に使うと、C<%> は単にビットを加えるので、これは
1360     セットされているビットを効率的に数えるためのよい方法となります:
1361    
1362     my $bitcount = unpack( '%32b*', $mask );
1363    
1364     =begin original
1365    
1366     And an even parity bit can be determined like this:
1367    
1368     =end original
1369    
1370     そして偶数パリティビットは以下のようにして決定できます:
1371    
1372     my $evenparity = unpack( '%1b*', $mask );
1373    
1374     =head2 Unicode
1375    
1376     =begin original
1377    
1378     Unicode is a character set that can represent most characters in most of
1379     the world's languages, providing room for over one million different
1380     characters. Unicode 3.1 specifies 94,140 characters: The Basic Latin
1381     characters are assigned to the numbers 0 - 127. The Latin-1 Supplement with
1382     characters that are used in several European languages is in the next
1383     range, up to 255. After some more Latin extensions we find the character
1384     sets from languages using non-Roman alphabets, interspersed with a
1385     variety of symbol sets such as currency symbols, Zapf Dingbats or Braille.
1386     (You might want to visit L<http://www.unicode.org/> for a look at some of
1387     them - my personal favourites are Telugu and Kannada.)
1388    
1389     =end original
1390    
1391     Unicode は世界中のほとんどの言語のほとんどの文字を表現できる文字集合で、
1392     100 万以上の異なった文字のための空間を提供しています。
1393     Unicode 3.1 は 94,140 文字を定義しています: 基本ラテン文字は番号
1394     0 - 127 に割り当てられています。
1395     いくつかのヨーロッパ言語で使われるラテン 1 補助が次の範囲で、255 までです。
1396     いくつかのラテン拡張の後、非ローマアルファベットを使う言語の文字集合
1397     および、通貨記号、Zapf Dingbats、点字のような様々な記号集合が
1398     散らばっています。
1399     (これらのいくつかを見るために L<http://www.unicode.org/> を訪れるのも
1400     良いでしょう - 私の個人的なお気に入りは Telugu と Kannada です。)
1401    
1402     =begin original
1403    
1404     The Unicode character sets associates characters with integers. Encoding
1405     these numbers in an equal number of bytes would more than double the
1406     requirements for storing texts written in Latin alphabets.
1407     The UTF-8 encoding avoids this by storing the most common (from a western
1408     point of view) characters in a single byte while encoding the rarer
1409     ones in three or more bytes.
1410    
1411     =end original
1412    
1413     Unicode 文字集合は文字と整数を結び付けます。
1414     これらの数値を同じバイト数でエンコードすると、ラテンアルファベットで
1415     書かれたテキストを保管するのに 2 倍以上のバイト数が必要になります。
1416     UTF-8 エンコーディングは(西洋からの視点において)もっとも共通の文字を
1417     1 バイトに格納し、より稀なものを 3 バイト以上にエンコードすることで
1418     これを回避しています。
1419    
1420     =begin original
1421    
1422     Perl uses UTF-8, internally, for most Unicode strings.
1423    
1424     =end original
1425    
1426     Perl はほとんどの Unicode 文字列に対して内部的に UTF-8 を使います。
1427    
1428     =begin original
1429    
1430     So what has this got to do with C<pack>? Well, if you want to compose a
1431     Unicode string (that is internally encoded as UTF-8), you can do so by
1432     using template code C<U>. As an example, let's produce the Euro currency
1433    
1434     =end original
1435    
1436     それで、これで C<pack> は何ができるのでしょう?
1437     えっと、もし Unicode 文字列 (これは内部では UTF-8 で
1438     エンコードされています) を構成したいなら、テンプレートコード C<U> を
1439     使うことでできます。
1440     例として、ユーロ通貨記号 (コード番号 0x20AC) を生成してみましょう:
1441    
1442     $UTF8{Euro} = pack( 'U', 0x20AC );
1443     # Equivalent to: $UTF8{Euro} = "\x{20ac}";
1444    
1445     =begin original
1446    
1447     Inspecting C<$UTF8{Euro}> shows that it contains 3 bytes:
1448     "\xe2\x82\xac". However, it contains only 1 character, number 0x20AC.
1449     The round trip can be completed with C<unpack>:
1450    
1451     =end original
1452    
1453     C<$UTF8{Euro}> を検査すると、3 バイトであることがわかります:
1454     "\xe2\x82\xac" です。
1455     しかし、これは番号 0x20AC の 1 文字だけを含んでいます。
1456     往復は C<unpack> を使って完了します:
1457    
1458     $Unicode{Euro} = unpack( 'U', $UTF8{Euro} );
1459    
1460     =begin original
1461    
1462     Unpacking using the C<U> template code also works on UTF-8 encoded byte
1463     strings.
1464    
1465     =end original
1466    
1467     C<U> テンプレートコードを使った unpack テンプレートコードは
1468     UTF-8 エンコードされたバイト文字列に対しても動作します。
1469    
1470     =begin original
1471    
1472     Usually you'll want to pack or unpack UTF-8 strings:
1473    
1474     =end original
1475    
1476     普通は UTF-8 文字列を pack または unpack したいでしょう:
1477    
1478     # pack and unpack the Hebrew alphabet
1479     my $alefbet = pack( 'U*', 0x05d0..0x05ea );
1480     my @hebrew = unpack( 'U*', $utf );
1481    
1482     =begin original
1483    
1484     Please note: in the general case, you're better off using
1485     Encode::decode_utf8 to decode a UTF-8 encoded byte string to a Perl
1486     Unicode string, and Encode::encode_utf8 to encode a Perl Unicode string
1487     to UTF-8 bytes. These functions provide means of handling invalid byte
1488     sequences and generally have a friendlier interface.
1489    
1490     =end original
1491    
1492     注意: 一般的な場合には、UTF-8 エンコードされたバイト文字列を Perl の
1493     Unicode 文字列にデコードするには Encode::decode_utf8 を使い、
1494     Perl の Unicode 文字列を UTF-8 のバイト文字列にエンコードするには
1495     Encode::encode_utf8 を使った方がよいです。
1496     これらの関数は不正なバイト列を扱う手段を提供し、一般的により親切な
1497     インターフェースを持ちます。
1498    
1499     =head2 Another Portable Binary Encoding
1500    
1501     (その他の移植性のあるバイナリエンコーディング)
1502    
1503     =begin original
1504    
1505     The pack code C<w> has been added to support a portable binary data
1506     encoding scheme that goes way beyond simple integers. (Details can
1507     be found at L<http://Casbah.org/>, the Scarab project.) A BER (Binary Encoded
1508     Representation) compressed unsigned integer stores base 128
1509     digits, most significant digit first, with as few digits as possible.
1510     Bit eight (the high bit) is set on each byte except the last. There
1511     is no size limit to BER encoding, but Perl won't go to extremes.
1512    
1513     =end original
1514    
1515     pack コード C<w> は、単純な整数とは程遠い、移植性のある
1516     バイナリデータエンコーディングスキームに対応するために追加されました。
1517     (詳細については Scarab プロジェクト L<http://Casbah.org/> にあります。)
1518     BER (Binary Encoded Representation) 圧縮符号なし整数は 128 を基数として、
1519     最上位ビットを最初にして、可能な限り少ない桁になるように保管します。
1520     ビット 8 (最上位ビット) は、最後以外のバイトでセットされます。
1521     BER エンコーディングにはサイズ制限がありませんが、Perl は極端なことは
1522     しません。
1523    
1524     my $berbuf = pack( 'w*', 1, 128, 128+1, 128*128+127 );
1525    
1526     =begin original
1527    
1528     A hex dump of C<$berbuf>, with spaces inserted at the right places,
1529     shows 01 8100 8101 81807F. Since the last byte is always less than
1530     128, C<unpack> knows where to stop.
1531    
1532     =end original
1533    
1534     C<$berbuf> を、適切な位置に空白を入れつつ 16 進ダンプを取ると、
1535     01 8100 8101 81807F となります。
1536     最後のバイトは常に 128 より小さくなるので、C<unpack> は停止する位置が
1537     わかります。
1538    
1539     =head1 Template Grouping
1540    
1541     (テンプレートのグループ化)
1542    
1543     =begin original
1544    
1545     Prior to Perl 5.8, repetitions of templates had to be made by
1546     C<x>-multiplication of template strings. Now there is a better way as
1547     we may use the pack codes C<(> and C<)> combined with a repeat count.
1548     The C<unpack> template from the Stack Frame example can simply
1549     be written like this:
1550    
1551     =end original
1552    
1553     Perl 5.8 以前では、テンプレートの繰り返しはテンプレート文字列を C<x> 回
1554     繰り返すことで作る必要がありました。
1555     今では、pack コード C<(> と C<)> に繰り返し数を組み合わせて使うという
1556     よりよい方法があります。
1557     スタックフレームの例の C<unpack> テンプレートは単に以下のように書けます:
1558    
1559     unpack( 'v2 (vXXCC)5 v5', $frame )
1560    
1561     =begin original
1562    
1563     Let's explore this feature a little more. We'll begin with the equivalent of
1564    
1565     =end original
1566    
1567     この機能についてもうすこしだけ探求してみましょう。
1568     以下と等価なものから始めます:
1569    
1570     join( '', map( substr( $_, 0, 1 ), @str ) )
1571    
1572     =begin original
1573    
1574     which returns a string consisting of the first character from each string.
1575     Using pack, we can write
1576    
1577     =end original
1578    
1579     これは、それぞれの文字列の最初の文字からなる文字列を返します。
1580     pack を使うと、以下のように書けます:
1581    
1582     pack( '(A)'.@str, @str )
1583    
1584     =begin original
1585    
1586     or, because a repeat count C<*> means "repeat as often as required",
1587     simply
1588    
1589     =end original
1590    
1591     あるいは、繰り返し数 C<*> は「必要なだけ繰り返す」ことを意味するので、
1592     単に以下のようになります:
1593    
1594     pack( '(A)*', @str )
1595    
1596     =begin original
1597    
1598     (Note that the template C<A*> would only have packed C<$str[0]> in full
1599     length.)
1600    
1601     =end original
1602    
1603     (テンプレートは C<A*> は C<$str[0]> を 完全な長さで pack するだけという
1604     ことに注意してください。)
1605    
1606     =begin original
1607    
1608     To pack dates stored as triplets ( day, month, year ) in an array C<@dates>
1609     into a sequence of byte, byte, short integer we can write
1610    
1611     =end original
1612    
1613     配列 C<@dates> に 3 つ組 (日、月、年) として保管されている日付を
1614     バイト、バイト、short に pack するには、以下のように書きます
1615    
1616     $pd = pack( '(CCS)*', map( @$_, @dates ) );
1617    
1618     =begin original
1619    
1620     To swap pairs of characters in a string (with even length) one could use
1621     several techniques. First, let's use C<x> and C<X> to skip forward and back:
1622    
1623     =end original
1624    
1625     ある文字列の中の(同じ長さの)部分文字列の組を交換するには、いくつかの
1626     技が使えます。
1627     まず、読み飛ばして戻ってくるために C<x> と C<X> を使いましょう:
1628    
1629     $s = pack( '(A)*', unpack( '(xAXXAx)*', $s ) );
1630    
1631     =begin original
1632    
1633     We can also use C<@> to jump to an offset, with 0 being the position where
1634     we were when the last C<(> was encountered:
1635    
1636     =end original
1637    
1638     また、オフセットに飛ぶために C<@> も使えます; ここで 0 は最後に C<(> に
1639     遭遇した位置になります:
1640    
1641     $s = pack( '(A)*', unpack( '(@1A @0A @2)*', $s ) );
1642    
1643     =begin original
1644    
1645     Finally, there is also an entirely different approach by unpacking big
1646     endian shorts and packing them in the reverse byte order:
1647    
1648     =end original
1649    
1650     最後に、ビッグエンディアンの short として unpack して、逆のバイト順で
1651     pack するという、全く異なった手法もあります:
1652    
1653     $s = pack( '(v)*', unpack( '(n)*', $s );
1654    
1655     =head1 Lengths and Widths
1656    
1657     (長さと幅)
1658    
1659     =head2 String Lengths
1660    
1661     (文字列の長さ)
1662    
1663     =begin original
1664    
1665     In the previous section we've seen a network message that was constructed
1666     by prefixing the binary message length to the actual message. You'll find
1667     that packing a length followed by so many bytes of data is a
1668     frequently used recipe since appending a null byte won't work
1669     if a null byte may be part of the data. Here is an example where both
1670     techniques are used: after two null terminated strings with source and
1671     destination address, a Short Message (to a mobile phone) is sent after
1672     a length byte:
1673    
1674     =end original
1675    
1676     前の章で、実際のメッセージの前にメッセージの長さをバイナリで前置することで
1677     構成されたネットワークメッセージを見ました。
1678     NUL バイトを追加するという方法は、データの一部として NUL バイトが
1679     含まれているときには動作しないので、引き続くデータの長さを pack するという
1680     方法はよく見られます。
1681     以下は両方の技術を使った例です: 送り元と送り先のアドレスを示す 2 つの
1682     NUL 終端文字列の後、(携帯電話への)ショートメッセージがその長さの後に
1683     送られます:
1684    
1685     my $msg = pack( 'Z*Z*CA*', $src, $dst, length( $sm ), $sm );
1686    
1687     =begin original
1688    
1689     Unpacking this message can be done with the same template:
1690    
1691     =end original
1692    
1693     このメッセージを unpack するには同じテンプレートで可能です:
1694    
1695     ( $src, $dst, $len, $sm ) = unpack( 'Z*Z*CA*', $msg );
1696    
1697     =begin original
1698    
1699     There's a subtle trap lurking in the offing: Adding another field after
1700     the Short Message (in variable C<$sm>) is all right when packing, but this
1701     cannot be unpacked naively:
1702    
1703     =end original
1704    
1705     遠くに微妙な罠が顔を覗かせています: (変数 C<$sm> に入っている)
1706     ショートメッセージの後にフィールドを追加すると、pack は問題ありませんが、
1707     ネイティブに unpack 出来なくなります。
1708    
1709     # pack a message
1710     my $msg = pack( 'Z*Z*CA*C', $src, $dst, length( $sm ), $sm, $prio );
1711    
1712     # unpack fails - $prio remains undefined!
1713     ( $src, $dst, $len, $sm, $prio ) = unpack( 'Z*Z*CA*C', $msg );
1714    
1715     =begin original
1716    
1717     The pack code C<A*> gobbles up all remaining bytes, and C<$prio> remains
1718     undefined! Before we let disappointment dampen the morale: Perl's got
1719     the trump card to make this trick too, just a little further up the sleeve.
1720     Watch this:
1721    
1722     =end original
1723    
1724     pack コード C<A*> は残り全てのコードを読み込んでしまい、C<$prio> が
1725     未定義のままになってしまうのです!
1726     がっかりして士気をくじかれる前に: Perl はこのようなトリックに対しても
1727     切り札を持っています; もう少し袖をまくってください。
1728     これを見てください:
1729    
1730     # pack a message: ASCIIZ, ASCIIZ, length/string, byte
1731     my $msg = pack( 'Z* Z* C/A* C', $src, $dst, $sm, $prio );
1732    
1733     # unpack
1734     ( $src, $dst, $sm, $prio ) = unpack( 'Z* Z* C/A* C', $msg );
1735    
1736     =begin original
1737    
1738     Combining two pack codes with a slash (C</>) associates them with a single
1739     value from the argument list. In C<pack>, the length of the argument is
1740     taken and packed according to the first code while the argument itself
1741     is added after being converted with the template code after the slash.
1742     This saves us the trouble of inserting the C<length> call, but it is
1743     in C<unpack> where we really score: The value of the length byte marks the
1744     end of the string to be taken from the buffer. Since this combination
1745     doesn't make sense except when the second pack code isn't C<a*>, C<A*>
1746     or C<Z*>, Perl won't let you.
1747    
1748     =end original
1749    
1750     二つの pack コードをスラッシュ (C</>) で繋ぐことで、引数リストの 1 つの
1751     値と結び付けられます。
1752     C<pack> では、引数の長さが取られて最初のコードに従って pack される一方、
1753     引数自体はスラッシュの後のテンプレートコードによって変換された後
1754     追加されます。
1755     これは C<length> 呼び出しを挿入することによるトラブルを救いますが、
1756     本当に効果があるのは C<unpack> においてです: 長さを示すバイトの値は
1757     バッファから取られる文字列の末尾をマークします。
1758     この組み合わせは 2 つ目の pack コードが C<a*>, C<A*>, C<Z*> でない場合
1759     以外は意味がないので、Perl はそうはさせません。
1760    
1761     =begin original
1762    
1763     The pack code preceding C</> may be anything that's fit to represent a
1764     number: All the numeric binary pack codes, and even text codes such as
1765     C<A4> or C<Z*>:
1766    
1767     =end original
1768    
1769     C</> の前に置く pack コードは、数値を表現するのに適したものであれば
1770     なんでも使えます:
1771     全ての数値バイナリ pack コードおよび、C<A4> や C<Z*> のような
1772     テキストコードにも対応します:
1773    
1774     # pack/unpack a string preceded by its length in ASCII
1775     my $buf = pack( 'A4/A*', "Humpty-Dumpty" );
1776     # unpack $buf: '13 Humpty-Dumpty'
1777     my $txt = unpack( 'A4/A*', $buf );
1778    
1779     =begin original
1780    
1781     C</> is not implemented in Perls before 5.6, so if your code is required to
1782     work on older Perls you'll need to C<unpack( 'Z* Z* C')> to get the length,
1783     then use it to make a new unpack string. For example
1784    
1785     =end original
1786    
1787     C</> は 5.6 以前の Perl には実装されていないので、もし、より古い Perl で
1788     動作することが要求される場合は、長さを得るために C<unpack( 'Z* Z* C')> を
1789     使って、それから新しい unpack 文字列を作ってそれを使う必要があります。
1790     例えば:
1791    
1792     # pack a message: ASCIIZ, ASCIIZ, length, string, byte (5.005 compatible)
1793     my $msg = pack( 'Z* Z* C A* C', $src, $dst, length $sm, $sm, $prio );
1794    
1795     # unpack
1796     ( undef, undef, $len) = unpack( 'Z* Z* C', $msg );
1797     ($src, $dst, $sm, $prio) = unpack ( "Z* Z* x A$len C", $msg );
1798    
1799     =begin original
1800    
1801     But that second C<unpack> is rushing ahead. It isn't using a simple literal
1802     string for the template. So maybe we should introduce...
1803    
1804     =end original
1805    
1806     しかしこの 2 番目の C<unpack> は先走りました。
1807     これはテンプレートとして単純なリテラル文字列を使っていません。
1808     それでは説明するべきでしょう…
1809    
1810     =head2 Dynamic Templates
1811    
1812     (動的テンプレート)
1813    
1814     =begin original
1815    
1816     So far, we've seen literals used as templates. If the list of pack
1817     items doesn't have fixed length, an expression constructing the
1818     template is required (whenever, for some reason, C<()*> cannot be used).
1819     Here's an example: To store named string values in a way that can be
1820     conveniently parsed by a C program, we create a sequence of names and
1821     null terminated ASCII strings, with C<=> between the name and the value,
1822     followed by an additional delimiting null byte. Here's how:
1823    
1824     =end original
1825    
1826     これまでは、テンプレートとして使われるリテラルを見てきました。
1827     pack するアイテムのリストが固定長でない場合(何らかの理由で C<()*> が
1828     使えないなら)、テンプレートを構成する式が必要です。
1829     以下は例です: C プログラムで使いやすい形で名前付き文字列値を保管するために、
1830     一続きの名前と NUL 終端された ASCII 文字列を作ります;
1831     名前と値の間には C<=> を置いて、最後に追加のデリミタとなる NUL バイトを
1832     置きます。
1833     以下のようにします:
1834    
1835     my $env = pack( '(A*A*Z*)' . keys( %Env ) . 'C',
1836     map( { ( $_, '=', $Env{$_} ) } keys( %Env ) ), 0 );
1837    
1838     =begin original
1839    
1840     Let's examine the cogs of this byte mill, one by one. There's the C<map>
1841     call, creating the items we intend to stuff into the C<$env> buffer:
1842     to each key (in C<$_>) it adds the C<=> separator and the hash entry value.
1843     Each triplet is packed with the template code sequence C<A*A*Z*> that
1844     is repeated according to the number of keys. (Yes, that's what the C<keys>
1845     function returns in scalar context.) To get the very last null byte,
1846     we add a C<0> at the end of the C<pack> list, to be packed with C<C>.
1847     (Attentive readers may have noticed that we could have omitted the 0.)
1848    
1849     =end original
1850    
1851     このバイト処理機の要素を一つ一つ調査してみましょう。
1852     C<map> 呼び出しは、C<$env> バッファに入れることを想定している内容の
1853     アイテムを作成します:
1854     (C<$_> の) それぞれのキーについて、C<=> セパレータとハッシュエントリの値を
1855     追加します。
1856     それぞれの 3 つ組は、キーの数
1857     (はい、これは C<keys> 関数がスカラコンテキストで返すものです。)
1858     に従って繰り返されるテンプレートコードの
1859     並び C<A*A*Z*> で pack されます。
1860     まさに最後の NUL バイトを得るために、C<pack> リストの最後に C<C> で
1861     pack するための C<0> を追加します。
1862     (注意深い読者なら、この 0 は省略できることに気付いたかもしれません。)
1863    
1864     =begin original
1865    
1866     For the reverse operation, we'll have to determine the number of items
1867     in the buffer before we can let C<unpack> rip it apart:
1868    
1869     =end original
1870    
1871     逆操作のために、C<unpack> に分解させる前にバッファにあるアイテムの数を
1872     決定する必要があります:
1873    
1874     my $n = $env =~ tr/\0// - 1;
1875     my %env = map( split( /=/, $_ ), unpack( "(Z*)$n", $env ) );
1876    
1877     =begin original
1878    
1879     The C<tr> counts the null bytes. The C<unpack> call returns a list of
1880     name-value pairs each of which is taken apart in the C<map> block.
1881    
1882     =end original
1883    
1884     C<tr> はヌルバイトを数えます。
1885     C<unpack> 呼び出しは名前-値の組のリストを返し、そのそれぞれが
1886     C<map> ブロックで分割されます。
1887    
1888     =head2 Counting Repetitions
1889    
1890     (繰り返しを数える)
1891    
1892     =begin original
1893    
1894     Rather than storing a sentinel at the end of a data item (or a list of items),
1895     we could precede the data with a count. Again, we pack keys and values of
1896     a hash, preceding each with an unsigned short length count, and up front
1897     we store the number of pairs:
1898    
1899     =end original
1900    
1901     データアイテム(あるいはアイテムのリスト)の最後に見張りをおくのではなく、
1902     データの数を先においておくこともできます。
1903     再び、ハッシュのキーと値を pack します; それぞれの前には符号なし short で
1904     長さが置かれ、先頭には組の数を保管します:
1905    
1906     my $env = pack( 'S(S/A* S/A*)*', scalar keys( %Env ), %Env );
1907    
1908     =begin original
1909    
1910     This simplifies the reverse operation as the number of repetitions can be
1911     unpacked with the C</> code:
1912    
1913     =end original
1914    
1915     繰り返し数は C</> コードで unpack できるので、逆操作は単純になります:
1916    
1917     my %env = unpack( 'S/(S/A* S/A*)', $env );
1918    
1919     =begin original
1920    
1921     Note that this is one of the rare cases where you cannot use the same
1922     template for C<pack> and C<unpack> because C<pack> can't determine
1923     a repeat count for a C<()>-group.
1924    
1925     =end original
1926    
1927     これは、C<pack> は C<()> グループの繰り返し数を決定できないので、
1928     C<pack> と C<unpack> で同じテンプレートが使えない珍しい場合であることに
1929     注意してください。
1930    
1931     =head1 Packing and Unpacking C Structures
1932    
1933     (C の構造体を pack/unpack する)
1934    
1935     =begin original
1936    
1937     In previous sections we have seen how to pack numbers and character
1938     strings. If it were not for a couple of snags we could conclude this
1939     section right away with the terse remark that C structures don't
1940     contain anything else, and therefore you already know all there is to it.
1941     Sorry, no: read on, please.
1942    
1943     =end original
1944    
1945     前のセクションで、数値と文字列を pack する方法を見ました。
1946     もしここに障害がないなら、「C 構造体には他に何もなく、従ってあなたは
1947     既に C 構造体を pack/unpack するための全てを知っています。」
1948     という簡潔な見解と共にこの章をすぐに締めくくることができます。
1949     すみません、そうではありません: どうか読み進めてください。
1950    
1951     =begin original
1952    
1953     If you have to deal with a lot of C structures, and don't want to
1954     hack all your template strings manually, you'll probably want to have
1955     a look at the CPAN module C<Convert::Binary::C>. Not only can it parse
1956     your C source directly, but it also has built-in support for all the
1957     odds and ends described further on in this section.
1958    
1959     =end original
1960    
1961     もし大量の C 構造体を扱う必要があって、全てのテンプレート文字列を手動で
1962     ハックしたくないなら、おそらく一度 CPAN モジュール C<Convert::Binary::C> を
1963     見たほうが良いでしょう。
1964     C ソースを直接パースできるだけでなく、この章でさらに記述される全ての
1965     雑務に対する組み込みのサポートがあります。
1966    
1967     =head2 The Alignment Pit
1968    
1969     (アライメントの落とし穴)
1970    
1971     =begin original
1972    
1973     In the consideration of speed against memory requirements the balance
1974     has been tilted in favor of faster execution. This has influenced the
1975     way C compilers allocate memory for structures: On architectures
1976     where a 16-bit or 32-bit operand can be moved faster between places in
1977     memory, or to or from a CPU register, if it is aligned at an even or
1978     multiple-of-four or even at a multiple-of eight address, a C compiler
1979     will give you this speed benefit by stuffing extra bytes into structures.
1980     If you don't cross the C shoreline this is not likely to cause you any
1981     grief (although you should care when you design large data structures,
1982     or you want your code to be portable between architectures (you do want
1983     that, don't you?)).
1984    
1985     =end original
1986    
1987     速度とメモリ消費のバランスは、より速く実行できる方に傾いています。
1988     これは C コンパイラが構造体のためにメモリを割り当てる方法に影響します:
1989     偶数、4 の倍数、あるいは 8 の倍数のアドレスにアライメントされていれば、
1990     16 ビットや 32 ビットのオペランドや CPU レジスタへの出し入れが速くなる
1991     アーキテクチャでは、C コンパイラは構造体に追加のバイトを入れることで
1992     この速度メリットを受けるようにします。
1993     もし C の海岸線を越えないのなら、これがなんらかの面倒を引き起こすことは
1994     ありそうにありません (しかし、大きなデータ構造を設計したり、
1995     アーキテクチャ間で移植性のあるコードがほしい場合(そうしたくないですか?)、
1996     気にするべきです。)。
1997    
1998     =begin original
1999    
2000     To see how this affects C<pack> and C<unpack>, we'll compare these two
2001     C structures:
2002    
2003     =end original
2004    
2005     これが C<pack> と C<unpack> にどのように影響を与えるかを見るために、
2006     これら 2 つの C 構造体を比較してみます:
2007    
2008     typedef struct {
2009     char c1;
2010     short s;
2011     char c2;
2012     long l;
2013     } gappy_t;
2014    
2015     typedef struct {
2016     long l;
2017     short s;
2018     char c1;
2019     char c2;
2020     } dense_t;
2021    
2022     =begin original
2023    
2024     Typically, a C compiler allocates 12 bytes to a C<gappy_t> variable, but
2025     requires only 8 bytes for a C<dense_t>. After investigating this further,
2026     we can draw memory maps, showing where the extra 4 bytes are hidden:
2027    
2028     =end original
2029    
2030     典型的には、C コンパイラは C<gappy_t> 変数には 12 バイトを割り当てますが、
2031     C<dense_t> には 8 バイトしか割り当てません。
2032     これをさらに調査した後、余分な 4 バイトが隠れていることが分かる
2033     メモリマップが書けます:
2034    
2035     0 +4 +8 +12
2036     +--+--+--+--+--+--+--+--+--+--+--+--+
2037     |c1|xx| s |c2|xx|xx|xx| l | xx = fill byte
2038     +--+--+--+--+--+--+--+--+--+--+--+--+
2039     gappy_t
2040    
2041     0 +4 +8
2042     +--+--+--+--+--+--+--+--+
2043     | l | h |c1|c2|
2044     +--+--+--+--+--+--+--+--+
2045     dense_t
2046    
2047     =begin original
2048    
2049     And that's where the first quirk strikes: C<pack> and C<unpack>
2050     templates have to be stuffed with C<x> codes to get those extra fill bytes.
2051    
2052     =end original
2053    
2054     そしてこれが最初の思いがけない一撃の理由です:
2055     C<pack> と C<unpack> のテンプレートは、これらの余分に埋めるバイトのために
2056     C<X> コードを詰める必要があります。
2057    
2058     =begin original
2059    
2060     The natural question: "Why can't Perl compensate for the gaps?" warrants
2061     an answer. One good reason is that C compilers might provide (non-ANSI)
2062     extensions permitting all sorts of fancy control over the way structures
2063     are aligned, even at the level of an individual structure field. And, if
2064     this were not enough, there is an insidious thing called C<union> where
2065     the amount of fill bytes cannot be derived from the alignment of the next
2066     item alone.
2067    
2068     =end original
2069    
2070     自然な質問: 「なぜ Perl は隙間を埋め合わせられないの?」には答えるのが
2071     当然です。
2072     一つのよい理由は、個々の構造体フィールドのレベルでさえ、構造体の
2073     アライメント方法のあらゆる種類の制御方法を許している(非 ANSI の)拡張を
2074     提供しているCコンパイラがあるからです。
2075     そして、もしこれが十分でないなら、埋めるバイト数が次のアイテムの
2076     アライメントだけでは決定されない、C<union> と呼ばれる
2077     陰険なものがあります。
2078    
2079     =begin original
2080    
2081     OK, so let's bite the bullet. Here's one way to get the alignment right
2082     by inserting template codes C<x>, which don't take a corresponding item
2083     from the list:
2084    
2085     =end original
2086    
2087     よし、では困難に耐えましょう。
2088     これは、リストから対応する要素を使わないテンプレートコード C<x> を
2089     挿入することでアライメントを正しくする一つの方法です:
2090    
2091     my $gappy = pack( 'cxs cxxx l!', $c1, $s, $c2, $l );
2092    
2093     =begin original
2094    
2095     Note the C<!> after C<l>: We want to make sure that we pack a long
2096     integer as it is compiled by our C compiler. And even now, it will only
2097     work for the platforms where the compiler aligns things as above.
2098     And somebody somewhere has a platform where it doesn't.
2099     [Probably a Cray, where C<short>s, C<int>s and C<long>s are all 8 bytes. :-)]
2100    
2101     =end original
2102    
2103     C<l> の後の C<!> に注意してください: long 整数を C コンパイラで
2104     コンパイルされるのと同じ形になるのを確実にしたいです。
2105     そしてこの時点でも、これはコンパイラが上述のようにアライメントする
2106     プラットフォームでのみ動作します。
2107     そしてどこかの誰かはそうでないプラットフォームを使っています。
2108     [おそらくは、Cray です; これは C<short>, C<int>, C<long> が全て
2109     8 バイトです。:-)]
2110    
2111     =begin original
2112    
2113     Counting bytes and watching alignments in lengthy structures is bound to
2114     be a drag. Isn't there a way we can create the template with a simple
2115     program? Here's a C program that does the trick:
2116    
2117     =end original
2118    
2119     とても長い構造体のバイト数を数えてアライメントを監視するのは面倒なことです。
2120     単純なプログラムでテンプレートを作る方法はないでしょうか?
2121     以下は技を使った C プログラムです:
2122    
2123     #include <stdio.h>
2124     #include <stddef.h>
2125    
2126     typedef struct {
2127     char fc1;
2128     short fs;
2129     char fc2;
2130     long fl;
2131     } gappy_t;
2132    
2133     #define Pt(struct,field,tchar) \
2134     printf( "@%d%s ", offsetof(struct,field), # tchar );
2135    
2136     int main() {
2137     Pt( gappy_t, fc1, c );
2138     Pt( gappy_t, fs, s! );
2139     Pt( gappy_t, fc2, c );
2140     Pt( gappy_t, fl, l! );
2141     printf( "\n" );
2142     }
2143    
2144     =begin original
2145    
2146     The output line can be used as a template in a C<pack> or C<unpack> call:
2147    
2148     =end original
2149    
2150     出力行は C<pack> や C<unpack> 呼び出しのテンプレートとして使えます。
2151    
2152     my $gappy = pack( '@0c @2s! @4c @8l!', $c1, $s, $c2, $l );
2153    
2154     =begin original
2155    
2156     Gee, yet another template code - as if we hadn't plenty. But
2157     C<@> saves our day by enabling us to specify the offset from the beginning
2158     of the pack buffer to the next item: This is just the value
2159     the C<offsetof> macro (defined in C<E<lt>stddef.hE<gt>>) returns when
2160     given a C<struct> type and one of its field names ("member-designator" in
2161     C standardese).
2162    
2163     =end original
2164    
2165     げー、新しいテンプレートコードです - まだ十分ではありませんでした。
2166     しかし C<@> は次のアイテムのための pack バッファの先頭からのオフセットを
2167     指定できるようにすることで手間を省きます:
2168     これは単に、C<struct> 型とそのフィールド名(C 標準での「メンバ指定子」)を
2169     与えたときに (C<E<lt>stddef.hE<gt>> で定義されている)C<offsetof> マクロが
2170     返す値です。
2171    
2172     =begin original
2173    
2174     Neither using offsets nor adding C<x>'s to bridge the gaps is satisfactory.
2175     (Just imagine what happens if the structure changes.) What we really need
2176     is a way of saying "skip as many bytes as required to the next multiple of N".
2177     In fluent Templatese, you say this with C<x!N> where N is replaced by the
2178     appropriate value. Here's the next version of our struct packaging:
2179    
2180     =end original
2181    
2182     オフセットを使ったり、隙間を渡すために C<x> を追加することでは
2183     十分ではありません。
2184     (構造体が変更されたときに何が起こるかを単に想像してみてください。)
2185     本当に必要なものは、「次の N の倍数のバイトになるまでスキップする」と
2186     書く各方法です。
2187     雄弁なテンプレートでは、これは C<x!N> とできます (ここで N は適切な値
2188     に置き換えられます)。
2189     これは構造体のパッケージ化の次のバージョンです:
2190    
2191     my $gappy = pack( 'c x!2 s c x!4 l!', $c1, $s, $c2, $l );
2192    
2193     =begin original
2194    
2195     That's certainly better, but we still have to know how long all the
2196     integers are, and portability is far away. Rather than C<2>,
2197     for instance, we want to say "however long a short is". But this can be
2198     done by enclosing the appropriate pack code in brackets: C<[s]>. So, here's
2199     the very best we can do:
2200    
2201     =end original
2202    
2203     これは確実により良いものですが、未だに全ての整数の長さを知る必要があり、
2204     移植性とはかけ離れています。
2205     例えば、C<2> の代わりに、「とにかく short の長さ」と書きたいです。
2206     しかし、これは適切な pack コードを大かっこで囲むこと (C<[s]>) で
2207     可能です。
2208     それで、これはできる限り最良のものです:
2209    
2210     my $gappy = pack( 'c x![s] s c x![l!] l!', $c1, $s, $c2, $l );
2211    
2212     =head2 Dealing with Endian-ness
2213    
2214     (エンディアンを扱う)
2215    
2216     =begin original
2217    
2218     Now, imagine that we want to pack the data for a machine with a
2219     different byte-order. First, we'll have to figure out how big the data
2220     types on the target machine really are. Let's assume that the longs are
2221     32 bits wide and the shorts are 16 bits wide. You can then rewrite the
2222     template as:
2223    
2224     =end original
2225    
2226     ここで、異なるバイト順のマシンのためのデータを pack したいとします。
2227     まず、ターゲットマシンでの実際のデータ型の大きさを知る必要があります。
2228     long は 32 ビット幅で short が 16 ビット幅と仮定しましょう。
2229     ここでテンプレートは以下のように書き換えられます:
2230    
2231     my $gappy = pack( 'c x![s] s c x![l] l', $c1, $s, $c2, $l );
2232    
2233     =begin original
2234    
2235     If the target machine is little-endian, we could write:
2236    
2237     =end original
2238    
2239     もしターゲットマシンがリトルエンディアンなら、以下のように書けます:
2240    
2241     my $gappy = pack( 'c x![s] s< c x![l] l<', $c1, $s, $c2, $l );
2242    
2243     =begin original
2244    
2245     This forces the short and the long members to be little-endian, and is
2246     just fine if you don't have too many struct members. But we could also
2247     use the byte-order modifier on a group and write the following:
2248    
2249     =end original
2250    
2251     これは short と long のメンバをリトルエンディアンに強制し、もし
2252     あまり多くの構造体メンバがない場合は十分です。
2253     しかし、グループにバイト順修飾子を使うことも出来、以下のように書けます:
2254    
2255     my $gappy = pack( '( c x![s] s c x![l] l )<', $c1, $s, $c2, $l );
2256    
2257     =begin original
2258    
2259     This is not as short as before, but it makes it more obvious that we
2260     intend to have little-endian byte-order for a whole group, not only
2261     for individual template codes. It can also be more readable and easier
2262     to maintain.
2263    
2264     =end original
2265    
2266     これは以前ほど短くありませんが、ここのテンプレートだけでなく、グループ全体に
2267     リトルエンディアンのバイト順を意図していることがより明らかです。
2268     これはまたより読みやすく、管理もより簡単です。
2269    
2270     =head2 Alignment, Take 2
2271    
2272     (アライメント、第二幕)
2273    
2274     =begin original
2275    
2276     I'm afraid that we're not quite through with the alignment catch yet. The
2277     hydra raises another ugly head when you pack arrays of structures:
2278    
2279     =end original
2280    
2281     アライメントの捕捉について、十分に説明していないのではないかと
2282     心配しています。
2283     構造体の配列を pack しようとすると、ヒドラはまた別の醜い頭をもたげてきます。
2284    
2285     typedef struct {
2286     short count;
2287     char glyph;
2288     } cell_t;
2289    
2290     typedef cell_t buffer_t[BUFLEN];
2291    
2292     =begin original
2293    
2294     Where's the catch? Padding is neither required before the first field C<count>,
2295     nor between this and the next field C<glyph>, so why can't we simply pack
2296     like this:
2297    
2298     =end original
2299    
2300     どこに罠があるのでしょう?
2301     最初のフィールド C<count> の前や、これと次のフィールド C<glyph> の間に
2302     パッディングは不要です; それならなぜ以下のように簡単に
2303     pack できないのでしょう:
2304    
2305     # something goes wrong here:
2306     pack( 's!a' x @buffer,
2307     map{ ( $_->{count}, $_->{glyph} ) } @buffer );
2308    
2309     =begin original
2310    
2311     This packs C<3*@buffer> bytes, but it turns out that the size of
2312     C<buffer_t> is four times C<BUFLEN>! The moral of the story is that
2313     the required alignment of a structure or array is propagated to the
2314     next higher level where we have to consider padding I<at the end>
2315     of each component as well. Thus the correct template is:
2316    
2317     =end original
2318    
2319     これは C<3*@buffer> バイトに pack しますが、C<buffer_t> のサイズは
2320     C<BUFLEN> の 4 倍になるのです!
2321     このお話の教訓は、構造体や配列で必要なアライメントは、それぞれの要素の
2322     I<最後に> パッディングを考慮する必要がある場所で、より高いレベルに
2323     伝播するということです。
2324     従って、正しいテンプレートは:
2325    
2326     pack( 's!ax' x @buffer,
2327     map{ ( $_->{count}, $_->{glyph} ) } @buffer );
2328    
2329     =head2 Alignment, Take 3
2330    
2331     (アライメント、第三幕)
2332    
2333     =begin original
2334    
2335     And even if you take all the above into account, ANSI still lets this:
2336    
2337     =end original
2338    
2339     上記のことを全て頭に入れたとしても、ANSI は以下のような場合:
2340    
2341     typedef struct {
2342     char foo[2];
2343     } foo_t;
2344    
2345     =begin original
2346    
2347     vary in size. The alignment constraint of the structure can be greater than
2348     any of its elements. [And if you think that this doesn't affect anything
2349     common, dismember the next cellphone that you see. Many have ARM cores, and
2350     the ARM structure rules make C<sizeof (foo_t)> == 4]
2351    
2352     =end original
2353    
2354     サイズは様々であるとしています。
2355     構造のアライメント制約は、それぞれの要素よりも大きいかもしれません。
2356     [そしてもしこれが一般的には何も影響を与えないと考えているなら、
2357     次に見た携帯電話を分解してみてください。
2358     多くは ARM コアを使っていて、ARM 構造体ルールでは
2359     C<sizeof (foo_t)> == 4 となります]
2360    
2361     =head2 Pointers for How to Use Them
2362    
2363     (ポインタをどう扱うかのポインタ)
2364    
2365     =begin original
2366    
2367     The title of this section indicates the second problem you may run into
2368     sooner or later when you pack C structures. If the function you intend
2369     to call expects a, say, C<void *> value, you I<cannot> simply take
2370     a reference to a Perl variable. (Although that value certainly is a
2371     memory address, it's not the address where the variable's contents are
2372     stored.)
2373    
2374     =end original
2375    
2376     この章のタイトルは、C の構造体を pack するときに遅かれ早かれ出会うことになる
2377     2 番目の問題を指し示しています。
2378     呼び出そうとしている関数が、例えば、C<void *> の値を想定している場合、
2379     単純に Perl の変数のリファレンスを使うことは I<できません>。
2380     (確かに値はメモリアドレスですが、値の内容が保持されているアドレスでは
2381     ないからです。)
2382    
2383     =begin original
2384    
2385     Template code C<P> promises to pack a "pointer to a fixed length string".
2386     Isn't this what we want? Let's try:
2387    
2388     =end original
2389    
2390     テンプレートコード C<P> は、「固定長文字列へのポインタ」を pack することを
2391     約束します。
2392     これが望みのものではないですか?
2393     試してみましょう:
2394    
2395     # allocate some storage and pack a pointer to it
2396     my $memory = "\x00" x $size;
2397     my $memptr = pack( 'P', $memory );
2398    
2399     =begin original
2400    
2401     But wait: doesn't C<pack> just return a sequence of bytes? How can we pass this
2402     string of bytes to some C code expecting a pointer which is, after all,
2403     nothing but a number? The answer is simple: We have to obtain the numeric
2404     address from the bytes returned by C<pack>.
2405    
2406     =end original
2407    
2408     ちょっと待った: C<pack> は単にバイトシーケンスを返すのでは?
2409     どうやってこのバイトの文字列を、ポインタ、つまり結局は数値でしかないものを
2410     想定している C のコードに渡せるのでしょう?
2411     答えは単純です: C<pack> で返されたバイト列から数値のアドレスを得なければ
2412     なりません。
2413    
2414     my $ptr = unpack( 'L!', $memptr );
2415    
2416     =begin original
2417    
2418     Obviously this assumes that it is possible to typecast a pointer
2419     to an unsigned long and vice versa, which frequently works but should not
2420     be taken as a universal law. - Now that we have this pointer the next question
2421     is: How can we put it to good use? We need a call to some C function
2422     where a pointer is expected. The read(2) system call comes to mind:
2423    
2424     =end original
2425    
2426     明らかに、これはポインタから unsigned long への、およびその逆の型キャストが
2427     可能であることを仮定しています; これはしばしば動作しますが、普遍的な
2428     原則として扱うべきではありません。
2429     - ここでこのポインタを得ましたが、次の質問は: これをうまく使うには
2430     どうするのがよいでしょう?
2431     ポインタを想定している C 関数を呼び出す必要があります。
2432     read(2) システムコールが心に浮かびます:
2433    
2434     ssize_t read(int fd, void *buf, size_t count);
2435    
2436     =begin original
2437    
2438     After reading L<perlfunc> explaining how to use C<syscall> we can write
2439     this Perl function copying a file to standard output:
2440    
2441     =end original
2442    
2443     L<perlfunc> にある C<syscall> の使い方の説明を読んだ後、ファイルを
2444     標準出力にコピーする Perl 関数を書けます:
2445    
2446     require 'syscall.ph';
2447     sub cat($){
2448     my $path = shift();
2449     my $size = -s $path;
2450     my $memory = "\x00" x $size; # allocate some memory
2451     my $ptr = unpack( 'L', pack( 'P', $memory ) );
2452     open( F, $path ) || die( "$path: cannot open ($!)\n" );
2453     my $fd = fileno(F);
2454     my $res = syscall( &SYS_read, fileno(F), $ptr, $size );
2455     print $memory;
2456     close( F );
2457     }
2458    
2459     =begin original
2460    
2461     This is neither a specimen of simplicity nor a paragon of portability but
2462     it illustrates the point: We are able to sneak behind the scenes and
2463     access Perl's otherwise well-guarded memory! (Important note: Perl's
2464     C<syscall> does I<not> require you to construct pointers in this roundabout
2465     way. You simply pass a string variable, and Perl forwards the address.)
2466    
2467     =end original
2468    
2469     これは単純さの見本でもなければ移植性の模範でもありませんが、要点を
2470     示しています: 舞台裏に忍び込んで、その他の点では良く守られている Perl の
2471     メモリにアクセスできます!
2472     (重要な注意: Perl の C<syscall> は、この回りくどい方法でポインタを
2473     構成する必要は I<ありません> 。
2474     単に文字列変数を渡せば、Perl がアドレスを転送します。)
2475    
2476     =begin original
2477    
2478     How does C<unpack> with C<P> work? Imagine some pointer in the buffer
2479     about to be unpacked: If it isn't the null pointer (which will smartly
2480     produce the C<undef> value) we have a start address - but then what?
2481     Perl has no way of knowing how long this "fixed length string" is, so
2482     it's up to you to specify the actual size as an explicit length after C<P>.
2483    
2484     =end original
2485    
2486     C<unpack> では C<P> はどのように動作するのでしょう?
2487     unpack されようとしているバッファにあるポインタを想像します:
2488     もしそれが(賢く C<undef> 値を生成する)ヌルポインタでない場合、開始アドレスを
2489     得ることになります - でも、それで?
2490     Perl はこの「固定長文字列」の長さを知る方法がないので、C<P> の後ろに
2491     明示的な長さとして実際の大きさを指定する必要があります。
2492    
2493     my $mem = "abcdefghijklmn";
2494     print unpack( 'P5', pack( 'P', $mem ) ); # prints "abcde"
2495    
2496     =begin original
2497    
2498     As a consequence, C<pack> ignores any number or C<*> after C<P>.
2499    
2500     =end original
2501    
2502     結果として、C<pack> は C<P> の後の数値や C<*> を無視します。
2503    
2504     =begin original
2505    
2506     Now that we have seen C<P> at work, we might as well give C<p> a whirl.
2507     Why do we need a second template code for packing pointers at all? The
2508     answer lies behind the simple fact that an C<unpack> with C<p> promises
2509     a null-terminated string starting at the address taken from the buffer,
2510     and that implies a length for the data item to be returned:
2511    
2512     =end original
2513    
2514     ここで C<P> の動作は見たので、同様に C<p> を試してみます。
2515     とにかく、なぜポインタを pack するのに 2 番目のテンプレートコードが
2516     必要なのでしょう?
2517     答えは、
2518     C<unpack> の C<p> はバッファから取った NUL 終端された文字列がその
2519     アドレスから始まっていることを約束していて、返されるデータアイテムの
2520     長さを暗示しているという単純な事実の後ろに横たわっています:
2521    
2522     my $buf = pack( 'p', "abc\x00efhijklmn" );
2523     print unpack( 'p', $buf ); # prints "abc"
2524    
2525     =begin original
2526    
2527     Albeit this is apt to be confusing: As a consequence of the length being
2528     implied by the string's length, a number after pack code C<p> is a repeat
2529     count, not a length as after C<P>.
2530    
2531     =end original
2532    
2533     それでもこれは混乱しがちです: 長さが文字列の長さを暗示しているので、
2534     C<p> の後の数値は繰り返し数であって、C<P> の後のように長さではありません。
2535    
2536     =begin original
2537    
2538     Using C<pack(..., $x)> with C<P> or C<p> to get the address where C<$x> is
2539     actually stored must be used with circumspection. Perl's internal machinery
2540     considers the relation between a variable and that address as its very own
2541     private matter and doesn't really care that we have obtained a copy. Therefore:
2542    
2543     =end original
2544    
2545     C<$x> が実際に保管されているアドレスを得るために C<pack(..., $x)> で
2546     C<P> や C<p> を使うことは慎重に行われなければなりません。
2547     Perl の内部機構は変数とそのアドレスの関係をとてもプライベートな問題と
2548     考え、私たちがコピーを得たことを実際には気にしません。
2549     従って:
2550    
2551     =over 4
2552    
2553     =item *
2554    
2555     =begin original
2556    
2557     Do not use C<pack> with C<p> or C<P> to obtain the address of variable
2558     that's bound to go out of scope (and thereby freeing its memory) before you
2559     are done with using the memory at that address.
2560    
2561     =end original
2562    
2563     その変数のアドレスのメモリを使い終わる前にスコープから出る(従って
2564     メモリが開放される)ような変数のアドレスを得るために
2565     C<pack> の C<p> や C<P> を使わないでください。
2566    
2567     =item *
2568    
2569     =begin original
2570    
2571     Be very careful with Perl operations that change the value of the
2572     variable. Appending something to the variable, for instance, might require
2573     reallocation of its storage, leaving you with a pointer into no-man's land.
2574    
2575     =end original
2576    
2577     変数の値を変更する Perl 操作にとても注意してください。
2578     例えば、値に何かを追加すると、その保管場所を再配置することになって、
2579     ポインタを誰もいないところにしたままにすることに
2580     なるかもしれません。
2581    
2582     =item *
2583    
2584     =begin original
2585    
2586     Don't think that you can get the address of a Perl variable
2587     when it is stored as an integer or double number! C<pack('P', $x)> will
2588     force the variable's internal representation to string, just as if you
2589     had written something like C<$x .= ''>.
2590    
2591     =end original
2592    
2593     整数や倍精度実数として保管されている Perl 変数のアドレスを取れるとは
2594     考えないでください!
2595     C<pack('P', $x)> は、ちょうど C<$x .= ''> のようなものを書いたのと同様に、
2596     変数の内部表現を文字列に強制します。
2597    
2598     =back
2599    
2600     =begin original
2601    
2602     It's safe, however, to P- or p-pack a string literal, because Perl simply
2603     allocates an anonymous variable.
2604    
2605     =end original
2606    
2607     しかし、文字列リテラルを P または p で pack することは安全です;
2608     なぜなら Perl は単に無名変数を割り当てるからです。
2609    
2610     =head1 Pack Recipes
2611    
2612     (pack レシピ)
2613    
2614     =begin original
2615    
2616     Here are a collection of (possibly) useful canned recipes for C<pack>
2617     and C<unpack>:
2618    
2619     =end original
2620    
2621     以下に C<pack> と C<unpack> に関する、(多分)役に立つレシピをまとめます:
2622    
2623     # Convert IP address for socket functions
2624     pack( "C4", split /\./, "123.4.5.6" );
2625    
2626     # Count the bits in a chunk of memory (e.g. a select vector)
2627     unpack( '%32b*', $mask );
2628    
2629     # Determine the endianness of your system
2630     $is_little_endian = unpack( 'c', pack( 's', 1 ) );
2631     $is_big_endian = unpack( 'xc', pack( 's', 1 ) );
2632    
2633     # Determine the number of bits in a native integer
2634     $bits = unpack( '%32I!', ~0 );
2635    
2636     # Prepare argument for the nanosleep system call
2637     my $timespec = pack( 'L!L!', $secs, $nanosecs );
2638    
2639     =begin original
2640    
2641     For a simple memory dump we unpack some bytes into just as
2642     many pairs of hex digits, and use C<map> to handle the traditional
2643     spacing - 16 bytes to a line:
2644    
2645     =end original
2646    
2647     単純なメモリダンプのために、バイト列を 16 進数の組に unpack し、
2648     C<map> を使って伝統的な表現 - 1 行に 16 バイト - に加工します:
2649    
2650     my $i;
2651     print map( ++$i % 16 ? "$_ " : "$_\n",
2652     unpack( 'H2' x length( $mem ), $mem ) ),
2653     length( $mem ) % 16 ? "\n" : '';
2654    
2655     =head1 Funnies Section
2656    
2657     (ネタ部門)
2658    
2659     # Pulling digits out of nowhere...
2660     print unpack( 'C', pack( 'x' ) ),
2661     unpack( '%B*', pack( 'A' ) ),
2662     unpack( 'H', pack( 'A' ) ),
2663     unpack( 'A', unpack( 'C', pack( 'A' ) ) ), "\n";
2664    
2665     # One for the road ;-)
2666     my $advice = pack( 'all u can in a van' );
2667    
2668     =head1 Authors
2669    
2670     (著者)
2671    
2672     =begin original
2673    
2674     Simon Cozens and Wolfgang Laun.
2675    
2676     =end original
2677    
2678     Simon Cozens と Wolfgang Laun。
2679    
2680     =begin meta
2681    
2682 argrath 1.2 Translate: Kentaro Shirakata <argrath@ub32.org> (5.8.8-)
2683 argrath 1.1
2684     =end meta
2685    

Back to OSDN">Back to OSDN
ViewVC Help
Powered by ViewVC 1.1.26