perlpacktut > 5.38.0 との差分

perlpacktut 5.38.0 と 5.10.0 の差分

11
2=encoding utf8
2=encoding euc-jp
33
44=head1 NAME
55
66=begin original
77
88perlpacktut - tutorial on C<pack> and C<unpack>
99
1010=end original
1111
1212perlpacktut - C<pack> と C<unpack> のチュートリアル
1313
1414=head1 DESCRIPTION
1515
1616=begin original
1717
1818C<pack> and C<unpack> are two functions for transforming data according
1919to a user-defined template, between the guarded way Perl stores values
2020and some well-defined representation as might be required in the
2121environment of a Perl program. Unfortunately, they're also two of
2222the most misunderstood and most often overlooked functions that Perl
2323provides. This tutorial will demystify them for you.
2424
2525=end original
2626
2727C<pack> と C<unpack> は、ユーザーが定義したテンプレートに従って、
2828Perl が値を保管する保護された方法と、Perl プログラムの環境で必要になる
2929かもしれないよく定義された表現の間を変換する二つの関数です。
3030残念ながら、これらは Perl が提供する関数の中でもっとも誤解され、
3131もっとも見落とされやすい関数でもあります。
3232このチュートリアルではこれらを分かりやすく説明します。
3333
3434=head1 The Basic Principle
3535
3636(基本原理)
3737
3838=begin original
3939
4040Most programming languages don't shelter the memory where variables are
4141stored. In C, for instance, you can take the address of some variable,
4242and the C<sizeof> operator tells you how many bytes are allocated to
4343the variable. Using the address and the size, you may access the storage
4444to your heart's content.
4545
4646=end original
4747
4848多くのプログラミング言語は変数が格納されているメモリを保護していません。
4949例えば、C では、ある変数のアドレスを取得できますし、
5050C<sizeof> 演算子は変数に何バイト割り当てられているかを返します。
5151アドレスとサイズを使って、心臓部にあるストレージにアクセスできます。
5252
5353=begin original
5454
5555In Perl, you just can't access memory at random, but the structural and
5656representational conversion provided by C<pack> and C<unpack> is an
5757excellent alternative. The C<pack> function converts values to a byte
5858sequence containing representations according to a given specification,
5959the so-called "template" argument. C<unpack> is the reverse process,
6060deriving some values from the contents of a string of bytes. (Be cautioned,
6161however, that not all that has been packed together can be neatly unpacked -
6262a very common experience as seasoned travellers are likely to confirm.)
6363
6464=end original
6565
6666Perl では、メモリにランダムにアクセスすることはできませんが、C<pack> と
6767C<unpack> によって提供される構造的および表現的な変換は素晴らしい
6868代替案です。
6969C<pack> 関数は、値を、「テンプレート」引数と呼ばれる使用に従った表現を含む
7070バイト列に変換します。
7171C<unpack> は逆処理で、バイトの並びから値を引き出します。
7272(しかし、pack された全てのデータがうまく unpack できるというわけでは
7373ないということは注意してください - 経験豊かな旅人が確認しそうな、とても
7474一般的な経験です。)
7575
7676=begin original
7777
7878Why, you may ask, would you need a chunk of memory containing some values
7979in binary representation? One good reason is input and output accessing
8080some file, a device, or a network connection, whereby this binary
8181representation is either forced on you or will give you some benefit
8282in processing. Another cause is passing data to some system call that
8383is not available as a Perl function: C<syscall> requires you to provide
8484parameters stored in the way it happens in a C program. Even text processing
8585(as shown in the next section) may be simplified with judicious usage
8686of these two functions.
8787
8888=end original
8989
9090あなたはどうしてバイナリ表現の中に値が含まれているメモリの塊が
9191必要なのか、と問うかもしれません。
9292よい理由の一つは、ファイル、デバイス、ネットワーク接続にアクセスする
9393入出力で、このバイナリ表現が強制されたものか、処理するためにいくらかの
9494利益がある場合です。
9595もう一つの原因は、Perl 関数として利用できないシステムコールにデータを
9696渡すときです: C<syscall> は C プログラムでのような形で保管された引数を
9797提供することを要求します。
9898(以下の章で示すように) テキスト処理ですら、これら 2 つの関数を賢明に
9999使うことで単純化できます。
100100
101101=begin original
102102
103103To see how (un)packing works, we'll start with a simple template
104104code where the conversion is in low gear: between the contents of a byte
105105sequence and a string of hexadecimal digits. Let's use C<unpack>, since
106106this is likely to remind you of a dump program, or some desperate last
107107message unfortunate programs are wont to throw at you before they expire
108108into the wild blue yonder. Assuming that the variable C<$mem> holds a
109109sequence of bytes that we'd like to inspect without assuming anything
110110about its meaning, we can write
111111
112112=end original
113113
114114(un)pack がどのように働くのかを見るために、変換がのろのろと行われる単純な
115115テンプレートコードから始めましょう: バイトシーケンスと 16 進数の文字列との
116116変換です。
117117C<unpack> を使いましょう; なぜならこれはダンププログラムや、
118118不幸なプログラムが息を引き取る前にあなたに投げかけることが常となっている
119119絶望的な最後のメッセージを思い出させそうだからです。
120120変数 C<$mem> に、その意味について何の仮定もおかずに調査したいバイト列が
121121入っていると仮定すると、以下のように書きます:
122122
123123 my( $hex ) = unpack( 'H*', $mem );
124124 print "$hex\n";
125125
126126=begin original
127127
128128whereupon we might see something like this, with each pair of hex digits
129129corresponding to a byte:
130130
131131=end original
132132
133133するとすぐに、1 バイトに対応して 16 進数 2 文字が対応する、以下のような
134134ものが表示されます:
135135
136136 41204d414e204120504c414e20412043414e414c2050414e414d41
137137
138138=begin original
139139
140140What was in this chunk of memory? Numbers, characters, or a mixture of
141141both? Assuming that we're on a computer where ASCII (or some similar)
142142encoding is used: hexadecimal values in the range C<0x40> - C<0x5A>
143143indicate an uppercase letter, and C<0x20> encodes a space. So we might
144144assume it is a piece of text, which some are able to read like a tabloid;
145145but others will have to get hold of an ASCII table and relive that
146146firstgrader feeling. Not caring too much about which way to read this,
147147we note that C<unpack> with the template code C<H> converts the contents
148148of a sequence of bytes into the customary hexadecimal notation. Since
149149"a sequence of" is a pretty vague indication of quantity, C<H> has been
150150defined to convert just a single hexadecimal digit unless it is followed
151151by a repeat count. An asterisk for the repeat count means to use whatever
152152remains.
153153
154154=end original
155155
156156このメモリの塊はなんでしょう?
157157数値、文字、あるいはそれらの混合でしょうか?
158158使っているコンピュータが ASCII エンコーディング (あるいは似たようなもの) を
159159使っていると仮定します: C<0x40> - C<0x5A> 範囲の 16 進数は大文字を
160160示していて、C<0x20> は空白をエンコードしたものです。
161161それで、これは、タブロイドのように読むことのできるテキストの断片と
162162仮定できます; その他は ASCII テーブルを持って 1 年生の感覚を思い出す
163163必要があります。
164164これをどのようにして読むかについてはあまり気にしないことにして、
165165C<unpack> のテンプレートコード C<H> はバイト列の内容をいつもの 16 進表記に
166166変換することに注目します。
167167「列」というのは量についてあいまいなので、
168168C<H> は、引き続いて繰り返し回数がない場合は単に 1 つの 16 進数を
169169変換するように定義されています。
170170繰り返し数でのアスタリスクは、残っているもの全てを使うことを意味します。
171171
172172=begin original
173173
174174The inverse operation - packing byte contents from a string of hexadecimal
175175digits - is just as easily written. For instance:
176176
177177=end original
178178
179179逆操作 - 16 進数の文字列からバイトの内容に pack する - は簡単に書けます。
180180例えば:
181181
182 my $s = pack( 'H2' x 10, 30..39 );
182 my $s = pack( 'H2' x 10, map { "3$_" } ( 0..9 ) );
183183 print "$s\n";
184184
185185=begin original
186186
187187Since we feed a list of ten 2-digit hexadecimal strings to C<pack>, the
188188pack template should contain ten pack codes. If this is run on a computer
189189with ASCII character coding, it will print C<0123456789>.
190190
191191=end original
192192
19319316 進で 2 桁の数値を示す文字列 10 個からなるリストを C<pack> に
194194渡しているので、pack テンプレートは 10 個の pack コードを含んでいる
195195必要があります。
196196これが ASCII 文字コードのコンピュータで実行されると、C<0123456789> を
197197表示します。
198198
199199=head1 Packing Text
200200
201201(テキストを pack する)
202202
203203=begin original
204204
205205Let's suppose you've got to read in a data file like this:
206206
207207=end original
208208
209209以下のようなデータファイルを読み込むことを考えます:
210210
211211 Date |Description | Income|Expenditure
212 01/24/2001 Zed's Camel Emporium 1147.99
212 01/24/2001 Ahmed's Camel Emporium 1147.99
213213 01/28/2001 Flea spray 24.99
214214 01/29/2001 Camel rides to tourists 235.00
215215
216216=begin original
217217
218218How do we do it? You might think first to use C<split>; however, since
219219C<split> collapses blank fields, you'll never know whether a record was
220220income or expenditure. Oops. Well, you could always use C<substr>:
221221
222222=end original
223223
224224どうすればいいでしょう?
225225最初に思いつくのは C<split> かもしれません;
226226しかし、C<split> は空白のフィールドを壊してしまうので、
227227そのレコードが収入だったか支出だったが分かりません。あらら。
228228では、C<substr> を使うとどうでしょう:
229229
230230 while (<>) {
231231 my $date = substr($_, 0, 11);
232232 my $desc = substr($_, 12, 27);
233233 my $income = substr($_, 40, 7);
234234 my $expend = substr($_, 52, 7);
235235 ...
236236 }
237237
238238=begin original
239239
240240It's not really a barrel of laughs, is it? In fact, it's worse than it
241241may seem; the eagle-eyed may notice that the first field should only be
24224210 characters wide, and the error has propagated right through the other
243243numbers - which we've had to count by hand. So it's error-prone as well
244244as horribly unfriendly.
245245
246246=end original
247247
248248これはあまり愉快ではないですよね?
249249実際、これは思ったより悪いです; 注意深い人は最初のフィールドが 10 文字分しか
250250なく、エラーが他の数値に拡大してしまう - 手で数えなければなりません -
251251ことに気付くでしょう。
252252従って、これは恐ろしく不親切であると同様、間違いが発生しやすいです.
253253
254254=begin original
255255
256256Or maybe we could use regular expressions:
257257
258258=end original
259259
260260あるいは正規表現も使えます:
261261
262262 while (<>) {
263263 my($date, $desc, $income, $expend) =
264264 m|(\d\d/\d\d/\d{4}) (.{27}) (.{7})(.*)|;
265265 ...
266266 }
267267
268268=begin original
269269
270270Urgh. Well, it's a bit better, but - well, would you want to maintain
271271that?
272272
273273=end original
274274
275うわあ。
275うわあ。えーと、少しましです。
276えーと、少しましです、しかし - えーと、これを保守したいと思います?
276しかし - えーと、これを保守したいと思います?
277277
278278=begin original
279279
280280Hey, isn't Perl supposed to make this sort of thing easy? Well, it does,
281281if you use the right tools. C<pack> and C<unpack> are designed to help
282282you out when dealing with fixed-width data like the above. Let's have a
283283look at a solution with C<unpack>:
284284
285285=end original
286286
287287ねえ、Perl はこの手のことを簡単にできないの?
288288ええ、できます、正しい道具を使えば。
289289C<pack> と C<unpack> は上記のような固定長データを扱う時の
290290助けになるように設計されています。
291291C<unpack> による解法を見てみましょう:
292292
293293 while (<>) {
294294 my($date, $desc, $income, $expend) = unpack("A10xA27xA7A*", $_);
295295 ...
296296 }
297297
298298=begin original
299299
300300That looks a bit nicer; but we've got to take apart that weird template.
301301Where did I pull that out of?
302302
303303=end original
304304
305305これはちょっとましに見えます;
306306でも変なテンプレートを分析しなければなりません。
307307これはどこから来たのでしょう?
308308
309309=begin original
310310
311311OK, let's have a look at some of our data again; in fact, we'll include
312312the headers, and a handy ruler so we can keep track of where we are.
313313
314314=end original
315315
316316よろしい、ここでデータをもう一度見てみましょう;
317317実際、ヘッダも含めて、何をしているかを追いかけるために
318318手書きの目盛りも付けています。
319319
320320 1 2 3 4 5
321321 1234567890123456789012345678901234567890123456789012345678
322322 Date |Description | Income|Expenditure
323323 01/28/2001 Flea spray 24.99
324324 01/29/2001 Camel rides to tourists 235.00
325325
326326=begin original
327327
328328From this, we can see that the date column stretches from column 1 to
329329column 10 - ten characters wide. The C<pack>-ese for "character" is
330330C<A>, and ten of them are C<A10>. So if we just wanted to extract the
331331dates, we could say this:
332332
333333=end original
334334
335335ここから、日付の桁は 1 桁目から 10 桁目まで - 10 文字の幅があることが
336336わかります。
337337「文字」のパックは C<A> で、10 文字の場合は C<A10> です。
338338それで、もし単に日付を展開したいだけなら、以下のように書けます:
339339
340340 my($date) = unpack("A10", $_);
341341
342342=begin original
343343
344344OK, what's next? Between the date and the description is a blank column;
345345we want to skip over that. The C<x> template means "skip forward", so we
346346want one of those. Next, we have another batch of characters, from 12 to
34734738. That's 27 more characters, hence C<A27>. (Don't make the fencepost
348348error - there are 27 characters between 12 and 38, not 26. Count 'em!)
349349
350350=end original
351351
352352よろしい、次は?
353353日付と説明の間には空白の桁があります;これは読み飛ばしたいです。
354354C<x> テンプレートは「読み飛ばす」ことを意味し、
355355これで 1 文字読み飛ばせます。
356356次に、別の文字の塊が 12 桁から 38 桁まであります。
357357これは 27 文字あるので、C<A27> です。
358358(数え間違えないように - 12 から 38 の間には 26 ではなく 27 文字あります。)
359359
360360=begin original
361361
362362Now we skip another character and pick up the next 7 characters:
363363
364364=end original
365365
366366次の文字は読み飛ばして、次の 7 文字を取り出します:
367367
368368 my($date,$description,$income) = unpack("A10xA27xA7", $_);
369369
370370=begin original
371371
372372Now comes the clever bit. Lines in our ledger which are just income and
373373not expenditure might end at column 46. Hence, we don't want to tell our
374374C<unpack> pattern that we B<need> to find another 12 characters; we'll
375375just say "if there's anything left, take it". As you might guess from
376376regular expressions, that's what the C<*> means: "use everything
377377remaining".
378378
379379=end original
380380
381381ここで少し賢くやりましょう。
382382台帳のうち、収入だけがあって支出がない行は 46 行目で終わっています。
383383従って、次の 12 文字を見つける B<必要がある> ということを
384384C<unpack> パターンに書きたくはありません;
385385単に次のようにします「もし何かが残っていれば、それを取ります」。
386386正規表現から推測したかもしれませんが、これが C<*> の意味することです:
387387「残っているもの全てを使います」。
388388
389389=over 3
390390
391391=item *
392392
393393=begin original
394394
395395Be warned, though, that unlike regular expressions, if the C<unpack>
396396template doesn't match the incoming data, Perl will scream and die.
397397
398398=end original
399399
400但し、正規表現とは違うことに注意してください; もし C<unpack> テンプレートが
400但し、正規表現とは違うことに注意してください
401入力データと一致しない場合、Perl は悲鳴をあげて die します。
401もし C<unpack> テンプレートが入力データと一致しない場合、
402Perl は悲鳴をあげて die します。
402403
403404=back
404405
405406=begin original
406407
407408Hence, putting it all together:
408409
409410=end original
410411
411412従って、これを全部あわせると:
412413
413 my ($date, $description, $income, $expend) =
414 my($date,$description,$income,$expend) = unpack("A10xA27xA7xA*", $_);
414 unpack("A10xA27xA7xA*", $_);
415415
416416=begin original
417417
418418Now, that's our data parsed. I suppose what we might want to do now is
419419total up our income and expenditure, and add another line to the end of
420420our ledger - in the same format - saying how much we've brought in and
421421how much we've spent:
422422
423423=end original
424424
425425これで、データがパースできます。
426426今ほしいものが収入と支出をそれぞれ足し合わせて、台帳の最後に - 同じ形式で -
4274271 行付け加えることで、どれだけの収入と支出があったかを記すことだとします:
428428
429429 while (<>) {
430 my ($date, $desc, $income, $expend) =
430 my($date, $desc, $income, $expend) = unpack("A10xA27xA7xA*", $_);
431 unpack("A10xA27xA7xA*", $_);
432431 $tot_income += $income;
433432 $tot_expend += $expend;
434433 }
435434
436435 $tot_income = sprintf("%.2f", $tot_income); # Get them into
437436 $tot_expend = sprintf("%.2f", $tot_expend); # "financial" format
438437
439438 $date = POSIX::strftime("%m/%d/%Y", localtime);
440439
441440 # OK, let's go:
442441
443 print pack("A10xA27xA7xA*", $date, "Totals",
442 print pack("A10xA27xA7xA*", $date, "Totals", $tot_income, $tot_expend);
444 $tot_income, $tot_expend);
445443
446444=begin original
447445
448446Oh, hmm. That didn't quite work. Let's see what happened:
449447
450448=end original
451449
452450あら、ふうむ。
453451これはうまく動きません。
454452何が起こったのか見てみましょう:
455453
456 01/24/2001 Zed's Camel Emporium 1147.99
454 01/24/2001 Ahmed's Camel Emporium 1147.99
457455 01/28/2001 Flea spray 24.99
458456 01/29/2001 Camel rides to tourists 1235.00
459457 03/23/2001Totals 1235.001172.98
460458
461459=begin original
462460
463461OK, it's a start, but what happened to the spaces? We put C<x>, didn't
464462we? Shouldn't it skip forward? Let's look at what L<perlfunc/pack> says:
465463
466464=end original
467465
468466まあ、これはスタートです; しかしスペースに何が起きたのでしょう?
469467C<x> を指定しましたよね?
470468これでは飛ばせない?
471469L<perlfunc/pack> に書いていることを見てみましょう:
472470
473471 x A null byte.
474472
475473=begin original
476474
477475Urgh. No wonder. There's a big difference between "a null byte",
478476character zero, and "a space", character 32. Perl's put something
479477between the date and the description - but unfortunately, we can't see
480478it!
481479
482480=end original
483481
484あ。
482あ。
485483当たり前です。
486484文字コード 0 の「ヌル文字」と、文字コード 32 の「空白」は全然違います。
487485Perl は日付と説明の間に何かを書いたのです - しかし残念ながら、
488486それは見えません!
489487
490488=begin original
491489
492490What we actually need to do is expand the width of the fields. The C<A>
493491format pads any non-existent characters with spaces, so we can use the
494492additional spaces to line up our fields, like this:
495493
496494=end original
497495
498496実際に必要なことはフィールドの幅を増やすことです。
499497C<A> フォーマットは存在しない文字を空白でパッディングするので、
500498以下のようにフィールドに空白の分だけ桁数を増やします:
501499
502 print pack("A11 A28 A8 A*", $date, "Totals",
500 print pack("A11 A28 A8 A*", $date, "Totals", $tot_income, $tot_expend);
503 $tot_income, $tot_expend);
504501
505502=begin original
506503
507504(Note that you can put spaces in the template to make it more readable,
508505but they don't translate to spaces in the output.) Here's what we got
509506this time:
510507
511508=end original
512509
513510(テンプレートには読みやすくするために空白を入れることができますが、
514511出力には反映されないことに注意してください。)
515512これで得られたのは以下のものです:
516513
517 01/24/2001 Zed's Camel Emporium 1147.99
514 01/24/2001 Ahmed's Camel Emporium 1147.99
518515 01/28/2001 Flea spray 24.99
519516 01/29/2001 Camel rides to tourists 1235.00
520517 03/23/2001 Totals 1235.00 1172.98
521518
522519=begin original
523520
524521That's a bit better, but we still have that last column which needs to
525522be moved further over. There's an easy way to fix this up:
526523unfortunately, we can't get C<pack> to right-justify our fields, but we
527524can get C<sprintf> to do it:
528525
529526=end original
530527
531528これで少し良くなりましたが、まだ、最後の桁をもっと向こうに移動させる
532529必要があります。
533530これを修正する簡単な方法があります:
534531残念ながら C<pack> でフィールドを右寄せにすることは出来ませんが、
535532C<sprintf> を使えば出来ます:
536533
537534 $tot_income = sprintf("%.2f", $tot_income);
538535 $tot_expend = sprintf("%12.2f", $tot_expend);
539536 $date = POSIX::strftime("%m/%d/%Y", localtime);
540 print pack("A11 A28 A8 A*", $date, "Totals",
537 print pack("A11 A28 A8 A*", $date, "Totals", $tot_income, $tot_expend);
541 $tot_income, $tot_expend);
542538
543539=begin original
544540
545541This time we get the right answer:
546542
547543=end original
548544
549545今度は正しい答えを得られました:
550546
551547 01/28/2001 Flea spray 24.99
552548 01/29/2001 Camel rides to tourists 1235.00
553549 03/23/2001 Totals 1235.00 1172.98
554550
555551=begin original
556552
557553So that's how we consume and produce fixed-width data. Let's recap what
558554we've seen of C<pack> and C<unpack> so far:
559555
560556=end original
561557
562558ということで、これが固定長データを読み書きする方法です。
563559ここまでで C<pack> と C<unpack> について見たことを復習しましょう:
564560
565561=over 3
566562
567563=item *
568564
569565=begin original
570566
571567Use C<pack> to go from several pieces of data to one fixed-width
572568version; use C<unpack> to turn a fixed-width-format string into several
573569pieces of data.
574570
575571=end original
576572
577573複数のデータ片を一つの固定長データにするには C<pack> を使います;
578574固定長フォーマット文字列を複数のデータ片にするには C<unpack> を使います。
579575
580576=item *
581577
582578=begin original
583579
584580The pack format C<A> means "any character"; if you're C<pack>ing and
585581you've run out of things to pack, C<pack> will fill the rest up with
586582spaces.
587583
588584=end original
589585
590586pack フォーマット C<A> は「任意の文字」を意味します; もし C<pack> 中に
591587pack するものがなくなったら、C<pack> は残りを空白で埋めます。
592588
593589=item *
594590
595591=begin original
596592
597593C<x> means "skip a byte" when C<unpack>ing; when C<pack>ing, it means
598594"introduce a null byte" - that's probably not what you mean if you're
599595dealing with plain text.
600596
601597=end original
602598
603599C<unpack> での C<x> は「1 バイト読み飛ばす」ことを意味します;
604600C<pack> では、「ヌルバイトを生成する」ことを意味します -
605601これは、プレーンテキストを扱っている場合はおそらく望んでいるものでは
606602ないでしょう。
607603
608604=item *
609605
610606=begin original
611607
612608You can follow the formats with numbers to say how many characters
613609should be affected by that format: C<A12> means "take 12 characters";
614610C<x6> means "skip 6 bytes" or "character 0, 6 times".
615611
616612=end original
617613
618614フォーマットの後に数値をつけることで、フォーマットに影響される文字数を
619615指定します: C<A12> は「12 文字取る」ことを意味します;
620616C<x6> は「6 バイト読み飛ばす」や「ヌルバイト 6 つ」を意味します。
621617
622618=item *
623619
624620=begin original
625621
626622Instead of a number, you can use C<*> to mean "consume everything else
627623left".
628624
629625=end original
630626
631627数値の代わりに、C<*> で「残っているもの全てを使う」ことを指定できます。
632628
633629=begin original
634630
635631B<Warning>: when packing multiple pieces of data, C<*> only means
636632"consume all of the current piece of data". That's to say
637633
638634=end original
639635
640636B<警告>: 複数のデータ片を pack するとき、C<*> は「現在のデータ片を全て
641637含む」という意味だけです。
642638これは、以下のようにすると:
643639
644640 pack("A*A*", $one, $two)
645641
646642=begin original
647643
648644packs all of C<$one> into the first C<A*> and then all of C<$two> into
649645the second. This is a general principle: each format character
650646corresponds to one piece of data to be C<pack>ed.
651647
652648=end original
653649
654650C<$one> の全てを最初の C<A*> に pack し、それから C<$two> の全てを二番目に
655651pack します。
656652ここに一般的な原則があります: 各フォーマット文字は C<pack> されるデータ片
657653一つに対応します。
658654
659655=back
660656
661657=head1 Packing Numbers
662658
663659(数値を pack する)
664660
665661=begin original
666662
667663So much for textual data. Let's get onto the meaty stuff that C<pack>
668664and C<unpack> are best at: handling binary formats for numbers. There is,
669665of course, not just one binary format - life would be too simple - but
670666Perl will do all the finicky labor for you.
671667
672668=end original
673669
674670テキストデータについてはこれくらいです。
675671C<pack> と C<unpack> が最良である、いやらしい代物: 数値のためのバイナリ
676672フォーマットに進みましょう。
677673もちろん、バイナリフォーマットはひとつではありません - 人生はそれほど
678674単純ではありません - が、Perl は全ての細かい作業を行います。
679675
680676=head2 Integers
681677
682678(整数)
683679
684680=begin original
685681
686682Packing and unpacking numbers implies conversion to and from some
687683I<specific> binary representation. Leaving floating point numbers
688684aside for the moment, the salient properties of any such representation
689685are:
690686
691687=end original
692688
693689数値を pack や unpack するということは、I<特定の> バイナリ表現との間で
694690変換するということを意味します。
695691今のところ浮動小数点数は脇にやっておくとすると、このような表現の
696692主要な性質としては:
697693
698694=over 4
699695
700696=item *
701697
702698=begin original
703699
704700the number of bytes used for storing the integer,
705701
706702=end original
707703
708704整数の保存に使うバイト数。
709705
710706=item *
711707
712708=begin original
713709
714710whether the contents are interpreted as a signed or unsigned number,
715711
716712=end original
717713
718714内容を符号なし数として解釈するか符号付き数として解釈するか。
719715
720716=item *
721717
722718=begin original
723719
724720the byte ordering: whether the first byte is the least or most
725721significant byte (or: little-endian or big-endian, respectively).
726722
727723=end original
728724
729725バイト順序:最初のバイトは最下位バイトか最上位バイトか
730726(言い換えると: それぞれリトルエンディアンかビッグエンディアンか)。
731727
732728=back
733729
734730=begin original
735731
736732So, for instance, to pack 20302 to a signed 16 bit integer in your
737733computer's representation you write
738734
739735=end original
740736
741737それで、例えば、20302 をあなたのコンピュータの符号付き 16 ビット整数に
742738pack するとすると、以下のように書きます:
743739
744740 my $ps = pack( 's', 20302 );
745741
746742=begin original
747743
748744Again, the result is a string, now containing 2 bytes. If you print
749745this string (which is, generally, not recommended) you might see
750746C<ON> or C<NO> (depending on your system's byte ordering) - or something
751747entirely different if your computer doesn't use ASCII character encoding.
752748Unpacking C<$ps> with the same template returns the original integer value:
753749
754750=end original
755751
756752再び、結果は 2 バイトからなる文字列です。
757753もしこの文字列を表示する(これは一般的にはお勧めできません)と、
758754C<ON> か C<NO> (システムのバイト順に依存します) - または、もし
759755コンピューターが ASCII 文字エンコーディングを使っていないなら全く違う
760756文字列が表示されます。
761757C<$ps> を同じテンプレートで unpack すると、元の整数値が返ります:
762758
763759 my( $s ) = unpack( 's', $ps );
764760
765761=begin original
766762
767763This is true for all numeric template codes. But don't expect miracles:
768764if the packed value exceeds the allotted byte capacity, high order bits
769765are silently discarded, and unpack certainly won't be able to pull them
770766back out of some magic hat. And, when you pack using a signed template
771767code such as C<s>, an excess value may result in the sign bit
772768getting set, and unpacking this will smartly return a negative value.
773769
774770=end original
775771
776772これは全ての数値テンプレートコードに対して真です。
777773しかし奇跡を期待してはいけません:
778774もし pack された値が割り当てられたバイト容量を超えると、高位ビットは
779775黙って捨てられ、unpack は確実に魔法の帽子からデータを
780776取り出すことができません。
781777そして、C<s> のような符号付きテンプレートコードを使って pack すると、
782778超えた値が符号ビットをセットすることになり、unpack すると負の値が
783779返されることになるかもしれません。
784780
785781=begin original
786782
78778316 bits won't get you too far with integers, but there is C<l> and C<L>
788784for signed and unsigned 32-bit integers. And if this is not enough and
789785your system supports 64 bit integers you can push the limits much closer
790786to infinity with pack codes C<q> and C<Q>. A notable exception is provided
791787by pack codes C<i> and C<I> for signed and unsigned integers of the
792788"local custom" variety: Such an integer will take up as many bytes as
793789a local C compiler returns for C<sizeof(int)>, but it'll use I<at least>
79479032 bits.
795791
796792=end original
797793
79879416 ビットは整数に十分とは言えませんが、符号付きと符号なしの 32 ビット
799795整数のための C<l> と C<L> もあります。
800796そして、これで十分ではなく、システムが 64 ビット整数に対応しているなら、
801797pack コード C<q> と C<Q> を使って限界をほぼ無限にまで押しやることができます。
802798注目すべき例外は pack コード C<i> と C<I> で、「ローカルに特化した」
803799符号付きと符号なしの整数を提供します: このような整数は C<sizeof(int)> と
804800したときにローカルな C コンパイラが返す値と同じバイト数ですが、
805801I<少なくとも> 32 ビットを使います。
806802
807803=begin original
808804
809805Each of the integer pack codes C<sSlLqQ> results in a fixed number of bytes,
810806no matter where you execute your program. This may be useful for some
811807applications, but it does not provide for a portable way to pass data
812808structures between Perl and C programs (bound to happen when you call
813809XS extensions or the Perl function C<syscall>), or when you read or
814810write binary files. What you'll need in this case are template codes that
815811depend on what your local C compiler compiles when you code C<short> or
816812C<unsigned long>, for instance. These codes and their corresponding
817813byte lengths are shown in the table below. Since the C standard leaves
818814much leeway with respect to the relative sizes of these data types, actual
819815values may vary, and that's why the values are given as expressions in
820816C and Perl. (If you'd like to use values from C<%Config> in your program
821817you have to import it with C<use Config>.)
822818
823819=end original
824820
825821整数 pack コード C<sSlLqQ> のそれぞれは、どこでプログラムが
826822実行されたとしても固定長のバイト列となります。
827823これは一部のアプリケーションでは有用ですが、(XS エクステンションや
828824Perl 関数 C<syscall> を呼び出すときに必要となる)
829825Perl と C のプログラムの間でデータ構造を渡す場合や、バイナリファイルを
830読み書きするときの、移植性のある手段は提供しません
826読み書きするときの、移植性のある手段は提供しません
831827この場合に必要なものは、例えば、C<short> や C<unsigned long> と書いたときに
832828ローカルの C コンパイラがどのようにコンパイルするかに依存する
833829テンプレートコードです。
834830これらのコードと、それに対応するバイト長は以下のテーブルの様になります。
835831C 標準はそれぞれのデータ型の大きさの点で多くの自由裁量を残しているので、
836832実際の値は異なるかもしれず、そしてこれがなぜ値が C と Perl の式として
837833与えられているかの理由です。
838834(もしプログラムで C<%Config> の値を使いたい場合は、C<use Config> として
839835これをインポートする必要があります。)
840836
841837=begin original
842838
843839 signed unsigned byte length in C byte length in Perl
844840 s! S! sizeof(short) $Config{shortsize}
845841 i! I! sizeof(int) $Config{intsize}
846842 l! L! sizeof(long) $Config{longsize}
847843 q! Q! sizeof(long long) $Config{longlongsize}
848844
849845=end original
850846
851847 符号付き 符号なし C でのバイト長 Perl でのバイト長
852848 s! S! sizeof(short) $Config{shortsize}
853849 i! I! sizeof(int) $Config{intsize}
854850 l! L! sizeof(long) $Config{longsize}
855851 q! Q! sizeof(long long) $Config{longlongsize}
856852
857853=begin original
858854
859855The C<i!> and C<I!> codes aren't different from C<i> and C<I>; they are
860856tolerated for completeness' sake.
861857
862858=end original
863859
864860C<i!> および C<I!> は C<i> および C<I> と違いはありません; これらは
865861完全性のために許容されています。
866862
867863=head2 Unpacking a Stack Frame
868864
869865(スタックフレームを unpack する)
870866
871867=begin original
872868
873869Requesting a particular byte ordering may be necessary when you work with
874870binary data coming from some specific architecture whereas your program could
875871run on a totally different system. As an example, assume you have 24 bytes
876872containing a stack frame as it happens on an Intel 8086:
877873
878874=end original
879875
880876特定のアーキテクチャから来たバイナリに対して作業をする一方、プログラムが
881877全く違うシステムで動いている場合、特定のバイト順序の要求が必要になります。
882878例として、Intel 8086 のスタックフレームを含む 24 バイトを仮定します:
883879
884880 +---------+ +----+----+ +---------+
885881 TOS: | IP | TOS+4:| FL | FH | FLAGS TOS+14:| SI |
886882 +---------+ +----+----+ +---------+
887883 | CS | | AL | AH | AX | DI |
888884 +---------+ +----+----+ +---------+
889885 | BL | BH | BX | BP |
890886 +----+----+ +---------+
891887 | CL | CH | CX | DS |
892888 +----+----+ +---------+
893889 | DL | DH | DX | ES |
894890 +----+----+ +---------+
895891
896892=begin original
897893
898894First, we note that this time-honored 16-bit CPU uses little-endian order,
899895and that's why the low order byte is stored at the lower address. To
900896unpack such a (unsigned) short we'll have to use code C<v>. A repeat
901897count unpacks all 12 shorts:
902898
903899=end original
904900
905901まず、この伝統のある 16 ビット CPU はリトルエンディアンを使っていて、
906902それが低位バイトが低位アドレスに格納されている理由であることに
907903注意します。
908904このような(符号付き)short を unpack するには、コード C<v> を使う必要が
909905あるでしょう。
910906繰り返し数によって、12 全ての short を unpack します。
911907
912 my( $ip, $cs, $flags, $ax, $bx, $cx, $dx, $si, $di, $bp, $ds, $es ) =
908 my( $ip, $cs, $flags, $ax, $bx, $cd, $dx, $si, $di, $bp, $ds, $es ) =
913909 unpack( 'v12', $frame );
914910
915911=begin original
916912
917913Alternatively, we could have used C<C> to unpack the individually
918914accessible byte registers FL, FH, AL, AH, etc.:
919915
920916=end original
921917
922918あるいは、FL, FH, AL, AH といったバイトレジスタに個々にアクセスできるように
923919unpack するための C<C> もあります:
924920
925921 my( $fl, $fh, $al, $ah, $bl, $bh, $cl, $ch, $dl, $dh ) =
926922 unpack( 'C10', substr( $frame, 4, 10 ) );
927923
928924=begin original
929925
930926It would be nice if we could do this in one fell swoop: unpack a short,
931927back up a little, and then unpack 2 bytes. Since Perl I<is> nice, it
932928proffers the template code C<X> to back up one byte. Putting this all
933929together, we may now write:
934930
935931=end original
936932
937933これを 1 回で行えたら素敵でしょう: short を unpack して、少し戻って、
938934それから 2 バイト unpack します。
939935Perl は I<素敵> なので、1 バイト戻るテンプレートコード C<X> を
940936提供しています。
941937これら全てを一緒にすると、以下のように書けます:
942938
943939 my( $ip, $cs,
944940 $flags,$fl,$fh,
945941 $ax,$al,$ah, $bx,$bl,$bh, $cx,$cl,$ch, $dx,$dl,$dh,
946942 $si, $di, $bp, $ds, $es ) =
947943 unpack( 'v2' . ('vXXCC' x 5) . 'v5', $frame );
948944
949945=begin original
950946
951947(The clumsy construction of the template can be avoided - just read on!)
952948
953949=end original
954950
955951(この不細工なテンプレート構造は避けられます - 読み進めてください!)
956952
957953=begin original
958954
959955We've taken some pains to construct the template so that it matches
960956the contents of our frame buffer. Otherwise we'd either get undefined values,
961957or C<unpack> could not unpack all. If C<pack> runs out of items, it will
962958supply null strings (which are coerced into zeroes whenever the pack code
963959says so).
964960
965961=end original
966962
967963テンプレートを構築するのに少し苦労したのは、フレームバッファの内容に
968964一致させるためです。
969965さもなければ未定義値を受け取ることになるか、あるいは
970966C<unpack> は何も unpack できなくなります。
971967もし C<pack> で要素がなくなったら、空文字列を補います
972968(pack コードがそうするように言っていれば、ゼロに強制されます)。
973969
974970=head2 How to Eat an Egg on a Net
975971
976972(インターネットの卵の食べ方)
977973
978974=begin original
979975
980976The pack code for big-endian (high order byte at the lowest address) is
981977C<n> for 16 bit and C<N> for 32 bit integers. You use these codes
982978if you know that your data comes from a compliant architecture, but,
983979surprisingly enough, you should also use these pack codes if you
984980exchange binary data, across the network, with some system that you
985981know next to nothing about. The simple reason is that this
986982order has been chosen as the I<network order>, and all standard-fearing
987983programs ought to follow this convention. (This is, of course, a stern
988984backing for one of the Lilliputian parties and may well influence the
989985political development there.) So, if the protocol expects you to send
990986a message by sending the length first, followed by just so many bytes,
991987you could write:
992988
993989=end original
994990
995991ビッグエンディアン(最下位アドレスが最上位バイト)での pack コードは、
99699216 ビット整数が C<n>、 32 ビット整数が C<N> です。
997993もし準拠したアーキテクチャからデータが来ることが分かっているなら
998994これらのコードを使います;
999995もしネットワークを通して何も知らない他のシステムとバイナリデータを
1000996交換する場合にもこれらの pack コードを使うべきです。
1001997理由は単純で、この順序が I<ネットワーク順序> として選ばれていて、標準を
1002998恐れる全てのプログラムがこの慣例に従っているはずだからです。
1003999(これはもちろん小人族の一行の一人の厳しい支援で、政治的な発展に
10041000影響を与えています。)
10051001それで、もし何バイトあるかの長さを先に送ることでメッセージを送ることを
10061002プロトコルが想定しているなら、以下のように書けます:
10071003
10081004 my $buf = pack( 'N', length( $msg ) ) . $msg;
10091005
10101006=begin original
10111007
10121008or even:
10131009
10141010=end original
10151011
10161012あるいは:
10171013
10181014 my $buf = pack( 'NA*', length( $msg ), $msg );
10191015
10201016=begin original
10211017
10221018and pass C<$buf> to your send routine. Some protocols demand that the
10231019count should include the length of the count itself: then just add 4
1024to the data length. (But make sure to read L</"Lengths and Widths"> before
1020to the data length. (But make sure to read L<"Lengths and Widths"> before
10251021you really code this!)
10261022
10271023=end original
10281024
10291025そして C<$buf> を送信ルーチンに渡します。
10301026カウントに、カウント自身の長さも含むことを要求しているプロトコルも
10311027あります: その時は単にデータ長に 4 を足してください。
1032(しかし、実際にこれをコーディングする前に L</"Lengths and Widths"> を
1028(しかし、実際にこれをコーディングする前に L<"Lengths and Widths"> を
10331029読んでください!)
10341030
10351031=head2 Byte-order modifiers
10361032
10371033(バイト順修飾子)
10381034
10391035=begin original
10401036
10411037In the previous sections we've learned how to use C<n>, C<N>, C<v> and
10421038C<V> to pack and unpack integers with big- or little-endian byte-order.
10431039While this is nice, it's still rather limited because it leaves out all
10441040kinds of signed integers as well as 64-bit integers. For example, if you
10451041wanted to unpack a sequence of signed big-endian 16-bit integers in a
10461042platform-independent way, you would have to write:
10471043
10481044=end original
10491045
10501046以前の章で、ビッグエンディアンとリトルエンディアンのバイト順の整数を
10511047pack および unpack するための C<n>, C<N>, C<v>, C<V> の使い方を学びました。
10521048これは素敵ですが、全ての種類の符号付き整数や、64 ビット整数が
10531049外れているので、まだいくらか制限されたものです。
10541050例えば、ビッグエンディアンの符号付き整数の並びをプラットフォームに
10551051依存しない方法で unpack したいとすると、以下のように書かなければなりません:
10561052
10571053 my @data = unpack 's*', pack 'S*', unpack 'n*', $buf;
10581054
10591055=begin original
10601056
10611057This is ugly. As of Perl 5.9.2, there's a much nicer way to express your
10621058desire for a certain byte-order: the C<E<gt>> and C<E<lt>> modifiers.
10631059C<E<gt>> is the big-endian modifier, while C<E<lt>> is the little-endian
10641060modifier. Using them, we could rewrite the above code as:
10651061
10661062=end original
10671063
10681064これは醜いです。
10691065Perl 5.9.2 から、バイト順に関して望み通りに記述するための、遥かに
10701066素敵な方法があります: C<E<gt>> と C<E<lt>> の修飾子です。
10711067C<E<gt>> はビッグエンディアン修飾子で、C<E<lt>> は
10721068リトルエンディアン修飾子です。
10731069これらを使うと、上述のコードは以下のように書き換えられます:
10741070
10751071 my @data = unpack 's>*', $buf;
10761072
10771073=begin original
10781074
10791075As you can see, the "big end" of the arrow touches the C<s>, which is a
10801076nice way to remember that C<E<gt>> is the big-endian modifier. The same
10811077obviously works for C<E<lt>>, where the "little end" touches the code.
10821078
10831079=end original
10841080
10851081見た通り、不等号の「大きい側」が C<s> に向いていて、C<E<gt>> が
10861082ビッグエンディアン修飾子であることを覚える素敵な方法となっています。
10871083明らかに同じことが、「小さい側」がコードに向いている C<E<lt>> にも働きます。
10881084
10891085=begin original
10901086
10911087You will probably find these modifiers even more useful if you have
10921088to deal with big- or little-endian C structures. Be sure to read
1093L</"Packing and Unpacking C Structures"> for more on that.
1089L<"Packing and Unpacking C Structures"> for more on that.
10941090
10951091=end original
10961092
10971093おそらく、これらの修飾子はビッグエンディアンやリトルエンディアンの C 構造体を
10981094扱うときにもっと便利であることに気付くでしょう。
1099これに関する詳細は、L</"Packing and Unpacking C Structures"> を
1095これに関する詳細は、L<"Packing and Unpacking C Structures"> を
11001096よく読んでください。
11011097
11021098=head2 Floating point Numbers
11031099
11041100(浮動小数点数)
11051101
11061102=begin original
11071103
11081104For packing floating point numbers you have the choice between the
11091105pack codes C<f>, C<d>, C<F> and C<D>. C<f> and C<d> pack into (or unpack
11101106from) single-precision or double-precision representation as it is provided
11111107by your system. If your systems supports it, C<D> can be used to pack and
1112unpack (C<long double>) values, which can offer even more resolution
1108unpack extended-precision floating point values (C<long double>), which
1113than C<f> or C<d>. B<Note that there are different long double formats.>
1109can offer even more resolution than C<f> or C<d>. C<F> packs an C<NV>,
1110which is the floating point type used by Perl internally. (There
1111is no such thing as a network representation for reals, so if you want
1112to send your real numbers across computer boundaries, you'd better stick
1113to ASCII representation, unless you're absolutely sure what's on the other
1114end of the line. For the even more adventuresome, you can use the byte-order
1115modifiers from the previous section also on floating point codes.)
11141116
11151117=end original
11161118
11171119浮動小数点数を pack するには、pack コード C<f>, C<d>, C<F>, C<D> の
11181120選択肢があります。
11191121C<f> と C<d> pack はシステムで提供されている単精度と倍精度の実数に
11201122pack (あるいは unpack) します。
11211123もしシステムが対応していれば、C<f> や C<d> より精度のある、
1122(C<long double>) の pack および unpack のために
1124拡張精度浮動小数点数 (C<long double>) の pack および unpack のために
11231125C<D> が使えます。
1124B<long double 型式は異なることに注意してください。>
1125
1126=begin original
1127
1128C<F> packs an C<NV>, which is the floating point type used by Perl
1129internally.
1130
1131=end original
1132
11331126C<F> は、Perl が内部で使用している浮動小数点型である C<NV> を pack します。
1127(実数に対してはネットワーク表現のようなものはないので、もし他の
1135=begin original
1136
1137There is no such thing as a network representation for reals, so if
1138you want to send your real numbers across computer boundaries, you'd
1139better stick to text representation, possibly using the hexadecimal
1140float format (avoiding the decimal conversion loss), unless you're
1141absolutely sure what's on the other end of the line. For the even more
1142adventuresome, you can use the byte-order modifiers from the previous
1143section also on floating point codes.
1144
1145=end original
1146
1147実数に対してはネットワーク表現のようなものはないので、もし他の
11481128コンピュータに実数を送りたい場合は、ネットワークの向こう側で何が起きるかが
1149完全に分かっているのでない限りは、テキスト表現
1129完全に分かっているのでない限りは、ASCII 表現で我慢した方がよいです。
1150(できれば(10 進変換のロスを防ぐために)16 進浮動小数点形式で) を守った方が
1151よいです。
11521130より冒険的な場合でも、以前の章で触れたバイト順修飾子を浮動小数点コードにも
1153使えます。
1131使えます。)
11541132
11551133=head1 Exotic Templates
11561134
11571135(風変わりなテンプレート)
11581136
11591137=head2 Bit Strings
11601138
11611139(ビット文字列)
11621140
11631141=begin original
11641142
11651143Bits are the atoms in the memory world. Access to individual bits may
11661144have to be used either as a last resort or because it is the most
11671145convenient way to handle your data. Bit string (un)packing converts
11681146between strings containing a series of C<0> and C<1> characters and
11691147a sequence of bytes each containing a group of 8 bits. This is almost
11701148as simple as it sounds, except that there are two ways the contents of
11711149a byte may be written as a bit string. Let's have a look at an annotated
11721150byte:
11731151
11741152=end original
11751153
11761154ビットはメモリの世界の原子です。
11771155個々のビットへのアクセスは、最後の手段として行われるか、それがデータを
11781156扱うのに最も便利な方法であるときに行われます。
11791157(un)pack したビット文字列は、C<0> と C<1> の文字からなる文字列と、
11801158それぞれ 8 ビットを含むバイト列とを変換します。
11811159バイトの内容をビット文字列として書くには 2 つの方法があるということを除けば、
11821160これはほとんど見たままの単純さです。
11831161以下の注釈付きのバイトを見てみましょう:
11841162
11851163 7 6 5 4 3 2 1 0
11861164 +-----------------+
11871165 | 1 0 0 0 1 1 0 0 |
11881166 +-----------------+
11891167 MSB LSB
11901168
11911169=begin original
11921170
11931171It's egg-eating all over again: Some think that as a bit string this should
11941172be written "10001100" i.e. beginning with the most significant bit, others
11951173insist on "00110001". Well, Perl isn't biased, so that's why we have two bit
11961174string codes:
11971175
11981176=end original
11991177
12001178卵の食べ方の繰り返しです: これは "10001100" というビット文字列になるべき、
12011179つまり最上位ビットから始めるべき、と考える人もいますし、
12021180"00110001" と主張する人もいます。
12031181ええ、Perl は偏向していないので、これが 2 つのビット文字列コードがある
12041182理由です:
12051183
12061184 $byte = pack( 'B8', '10001100' ); # start with MSB
12071185 $byte = pack( 'b8', '00110001' ); # start with LSB
12081186
12091187=begin original
12101188
12111189It is not possible to pack or unpack bit fields - just integral bytes.
12121190C<pack> always starts at the next byte boundary and "rounds up" to the
12131191next multiple of 8 by adding zero bits as required. (If you do want bit
12141192fields, there is L<perlfunc/vec>. Or you could implement bit field
12151193handling at the character string level, using split, substr, and
12161194concatenation on unpacked bit strings.)
12171195
12181196=end original
12191197
12201198ビットフィールドを pack や unpack することはできません -
12211199バイト単位だけです。
12221200C<pack> は常に次のバイト境界から始まり、必要な場合は 0 のビットを
12231201追加することで 8 の倍数に「切り上げ」られます。
12241202(もしビットフィールドがほしいなら、L<perlfunc/vec> があります。
12251203あるいは、split, substr および unpack したビット文字列の結合を使って
12261204文字単位のレベルでビットフィールド操作を実装することも出来ます。)
12271205
12281206=begin original
12291207
12301208To illustrate unpacking for bit strings, we'll decompose a simple
12311209status register (a "-" stands for a "reserved" bit):
12321210
12331211=end original
12341212
12351213ビット文字列の unpack を図示するために、単純な状態レジスタを分解してみます
12361214("-" は「予約された」ビットを意味します):
12371215
12381216 +-----------------+-----------------+
12391217 | S Z - A - P - C | - - - - O D I T |
12401218 +-----------------+-----------------+
12411219 MSB LSB MSB LSB
12421220
12431221=begin original
12441222
12451223Converting these two bytes to a string can be done with the unpack
12461224template C<'b16'>. To obtain the individual bit values from the bit
12471225string we use C<split> with the "empty" separator pattern which dissects
12481226into individual characters. Bit values from the "reserved" positions are
12491227simply assigned to C<undef>, a convenient notation for "I don't care where
12501228this goes".
12511229
12521230=end original
12531231
12541232これら 2 バイトから文字列への変換は unpack テンプレート C<'b16'> によって
12551233行われます。
12561234ビット文字列から個々のビット値を得るには、C<split> を「空」セパレータで
12571235使うことで個々の文字に切り刻みます。
12581236「予約された」位置からのビット値は単に C<undef> に代入しておきます;
12591237これは「この値がどこに行こうが気にしない」ことを示す便利な記法です。
12601238
12611239 ($carry, undef, $parity, undef, $auxcarry, undef, $zero, $sign,
12621240 $trace, $interrupt, $direction, $overflow) =
12631241 split( //, unpack( 'b16', $status ) );
12641242
12651243=begin original
12661244
12671245We could have used an unpack template C<'b12'> just as well, since the
12681246last 4 bits can be ignored anyway.
12691247
12701248=end original
12711249
12721250ちょうど同じように、unpack テンプレート C<'b12'> も使えます;
12731251最後の 4 ビットはどちらにしろ無視されるからです。
12741252
12751253=head2 Uuencoding
12761254
12771255(uuencode)
12781256
12791257=begin original
12801258
1281Another odd-man-out in the template alphabet is C<u>, which packs a
1259Another odd-man-out in the template alphabet is C<u>, which packs an
12821260"uuencoded string". ("uu" is short for Unix-to-Unix.) Chances are that
12831261you won't ever need this encoding technique which was invented to overcome
12841262the shortcomings of old-fashioned transmission mediums that do not support
12851263other than simple ASCII data. The essential recipe is simple: Take three
12861264bytes, or 24 bits. Split them into 4 six-packs, adding a space (0x20) to
12871265each. Repeat until all of the data is blended. Fold groups of 4 bytes into
12881266lines no longer than 60 and garnish them in front with the original byte count
12891267(incremented by 0x20) and a C<"\n"> at the end. - The C<pack> chef will
12901268prepare this for you, a la minute, when you select pack code C<u> on the menu:
12911269
12921270=end original
12931271
12941272テンプレートの中のもう一つの半端者は C<u> で、「uuencode された文字列」を
12951273pack します。
12961274("uu" は Unix-to-Unix を縮めたものです。)
12971275あなたには、単純な ASCII データしか対応していない旧式の通信メディアの欠点を
12981276克服するために開発されたこのエンコーディング技術が必要になる機会は
12991277なかったかもしれません。
13001278本質的なレシピは単純です: 3 バイト、つまり 24 ビットを取ります。
13011279これを 4 つの 6 ビットに分け、それぞれに空白 (0x20) を加えます。
13021280全てのデータが混ぜられるまで繰り返します。
130312814 バイトの組を 60 文字を超えない行に折り畳み、元のバイト数(0x20 を
13041282加えたもの)を先頭に置いて、末尾に C<"\n"> を置きます。
13051283- あなたがメニューから pack コード C<u> を選ぶと、C<pack> シェフは
13061284即席で、下ごしらえをしてくれます:
13071285
13081286 my $uubuf = pack( 'u', $bindat );
13091287
13101288=begin original
13111289
13121290A repeat count after C<u> sets the number of bytes to put into an
13131291uuencoded line, which is the maximum of 45 by default, but could be
13141292set to some (smaller) integer multiple of three. C<unpack> simply ignores
13151293the repeat count.
13161294
13171295=end original
13181296
13191297C<u> の後の繰り返し数は uuencode された行にいれるバイト数で、デフォルトでは
13201298最大の 45 ですが、3 の倍数のその他の(より小さい)数にできます。
13211299C<unpack> は単に繰り返し数を無視します。
13221300
13231301=head2 Doing Sums
13241302
13251303(合計を計算する)
13261304
13271305=begin original
13281306
13291307An even stranger template code is C<%>E<lt>I<number>E<gt>. First, because
13301308it's used as a prefix to some other template code. Second, because it
13311309cannot be used in C<pack> at all, and third, in C<unpack>, doesn't return the
13321310data as defined by the template code it precedes. Instead it'll give you an
13331311integer of I<number> bits that is computed from the data value by
13341312doing sums. For numeric unpack codes, no big feat is achieved:
13351313
13361314=end original
13371315
13381316さらに不思議なテンプレートコードは C<%>E<lt>I<number>E<gt> です。
13391317第一に、これはその他のテンプレートコードの前置詞として使われるからです。
13401318第二に、C<pack> では全く使えず、第三に、C<unpack> では、先行する
13411319テンプレートコードによって定義された値を返さないからです。
13421320代わりに、これはデータの合計として計算された I<number> ビットの整数を
13431321与えます。
13441322数値 unpack コードでは、大きな離れ業は行われません:
13451323
13461324 my $buf = pack( 'iii', 100, 20, 3 );
13471325 print unpack( '%32i3', $buf ), "\n"; # prints 123
13481326
13491327=begin original
13501328
13511329For string values, C<%> returns the sum of the byte values saving
13521330you the trouble of a sum loop with C<substr> and C<ord>:
13531331
13541332=end original
13551333
13561334文字列値に対しては、C<%> はバイト値の合計を返し、C<substr> と C<ord> による
13571335合計計算ループによる問題からあなたを救います:
13581336
13591337 print unpack( '%32A*', "\x01\x10" ), "\n"; # prints 17
13601338
13611339=begin original
13621340
13631341Although the C<%> code is documented as returning a "checksum":
13641342don't put your trust in such values! Even when applied to a small number
13651343of bytes, they won't guarantee a noticeable Hamming distance.
13661344
13671345=end original
13681346
13691347C<%> コードは「チェックサム」を返すと文書化されていますが:
13701348このような値に信頼を置いてはいけません!
13711349少量のバイト列に適用する場合ですら、顕著なハミング距離を保証できません。
13721350
13731351=begin original
13741352
13751353In connection with C<b> or C<B>, C<%> simply adds bits, and this can be put
13761354to good use to count set bits efficiently:
13771355
13781356=end original
13791357
13801358C<b> や C<B> と共に使うと、C<%> は単にビットを加えるので、これは
13811359セットされているビットを効率的に数えるためのよい方法となります:
13821360
13831361 my $bitcount = unpack( '%32b*', $mask );
13841362
13851363=begin original
13861364
13871365And an even parity bit can be determined like this:
13881366
13891367=end original
13901368
13911369そして偶数パリティビットは以下のようにして決定できます:
13921370
13931371 my $evenparity = unpack( '%1b*', $mask );
13941372
13951373=head2 Unicode
13961374
13971375=begin original
13981376
13991377Unicode is a character set that can represent most characters in most of
14001378the world's languages, providing room for over one million different
14011379characters. Unicode 3.1 specifies 94,140 characters: The Basic Latin
14021380characters are assigned to the numbers 0 - 127. The Latin-1 Supplement with
14031381characters that are used in several European languages is in the next
14041382range, up to 255. After some more Latin extensions we find the character
14051383sets from languages using non-Roman alphabets, interspersed with a
14061384variety of symbol sets such as currency symbols, Zapf Dingbats or Braille.
1407(You might want to visit L<https://www.unicode.org/> for a look at some of
1385(You might want to visit L<http://www.unicode.org/> for a look at some of
14081386them - my personal favourites are Telugu and Kannada.)
14091387
14101388=end original
14111389
14121390Unicode は世界中のほとんどの言語のほとんどの文字を表現できる文字集合で、
14131391100 万以上の異なった文字のための空間を提供しています。
14141392Unicode 3.1 は 94,140 文字を定義しています: 基本ラテン文字は番号
141513930 - 127 に割り当てられています。
14161394いくつかのヨーロッパ言語で使われるラテン 1 補助が次の範囲で、255 までです。
14171395いくつかのラテン拡張の後、非ローマアルファベットを使う言語の文字集合
14181396および、通貨記号、Zapf Dingbats、点字のような様々な記号集合が
14191397散らばっています。
1420(これらのいくつかを見るために L<https://www.unicode.org/> を訪れるのも
1398(これらのいくつかを見るために L<http://www.unicode.org/> を訪れるのも
14211399良いでしょう - 私の個人的なお気に入りは Telugu と Kannada です。)
14221400
14231401=begin original
14241402
14251403The Unicode character sets associates characters with integers. Encoding
14261404these numbers in an equal number of bytes would more than double the
14271405requirements for storing texts written in Latin alphabets.
14281406The UTF-8 encoding avoids this by storing the most common (from a western
14291407point of view) characters in a single byte while encoding the rarer
14301408ones in three or more bytes.
14311409
14321410=end original
14331411
14341412Unicode 文字集合は文字と整数を結び付けます。
14351413これらの数値を同じバイト数でエンコードすると、ラテンアルファベットで
14361414書かれたテキストを保管するのに 2 倍以上のバイト数が必要になります。
14371415UTF-8 エンコーディングは(西洋からの視点において)もっとも共通の文字を
143814161 バイトに格納し、より稀なものを 3 バイト以上にエンコードすることで
14391417これを回避しています。
14401418
14411419=begin original
14421420
14431421Perl uses UTF-8, internally, for most Unicode strings.
14441422
14451423=end original
14461424
14471425Perl はほとんどの Unicode 文字列に対して内部的に UTF-8 を使います。
14481426
14491427=begin original
14501428
14511429So what has this got to do with C<pack>? Well, if you want to compose a
14521430Unicode string (that is internally encoded as UTF-8), you can do so by
14531431using template code C<U>. As an example, let's produce the Euro currency
14541432symbol (code number 0x20AC):
14551433
14561434=end original
14571435
14581436それで、これで C<pack> は何ができるのでしょう?
14591437えっと、もし Unicode 文字列 (これは内部では UTF-8 で
14601438エンコードされています) を構成したいなら、テンプレートコード C<U> を
14611439使うことでできます。
14621440例として、ユーロ通貨記号 (コード番号 0x20AC) を生成してみましょう:
14631441
14641442 $UTF8{Euro} = pack( 'U', 0x20AC );
14651443 # Equivalent to: $UTF8{Euro} = "\x{20ac}";
14661444
14671445=begin original
14681446
14691447Inspecting C<$UTF8{Euro}> shows that it contains 3 bytes:
14701448"\xe2\x82\xac". However, it contains only 1 character, number 0x20AC.
14711449The round trip can be completed with C<unpack>:
14721450
14731451=end original
14741452
14751453C<$UTF8{Euro}> を検査すると、3 バイトであることがわかります:
14761454"\xe2\x82\xac" です。
14771455しかし、これは番号 0x20AC の 1 文字だけを含んでいます。
14781456往復は C<unpack> を使って完了します:
14791457
14801458 $Unicode{Euro} = unpack( 'U', $UTF8{Euro} );
14811459
14821460=begin original
14831461
14841462Unpacking using the C<U> template code also works on UTF-8 encoded byte
14851463strings.
14861464
14871465=end original
14881466
14891467C<U> テンプレートコードを使った unpack テンプレートコードは
14901468UTF-8 エンコードされたバイト文字列に対しても動作します。
14911469
14921470=begin original
14931471
14941472Usually you'll want to pack or unpack UTF-8 strings:
14951473
14961474=end original
14971475
14981476普通は UTF-8 文字列を pack または unpack したいでしょう:
14991477
15001478 # pack and unpack the Hebrew alphabet
15011479 my $alefbet = pack( 'U*', 0x05d0..0x05ea );
15021480 my @hebrew = unpack( 'U*', $utf );
15031481
15041482=begin original
15051483
15061484Please note: in the general case, you're better off using
1507L<C<Encode::decode('UTF-8', $utf)>|Encode/decode> to decode a UTF-8
1485Encode::decode_utf8 to decode a UTF-8 encoded byte string to a Perl
1508encoded byte string to a Perl Unicode string, and
1486Unicode string, and Encode::encode_utf8 to encode a Perl Unicode string
1509L<C<Encode::encode('UTF-8', $str)>|Encode/encode> to encode a Perl Unicode
1487to UTF-8 bytes. These functions provide means of handling invalid byte
1510string to UTF-8 bytes. These functions provide means of handling invalid byte
15111488sequences and generally have a friendlier interface.
15121489
15131490=end original
15141491
15151492注意: 一般的な場合には、UTF-8 エンコードされたバイト文字列を Perl の
1516Unicode 文字列にデコードするには
1493Unicode 文字列にデコードするには Encode::decode_utf8 を使い、
1517L<C<Encode::decode('UTF-8', $utf)>|Encode/decode> を使い、
15181494Perl の Unicode 文字列を UTF-8 のバイト文字列にエンコードするには
1519L<C<Encode::encode('UTF-8', $str)>|Encode/encode> を使った方がよいです。
1495Encode::encode_utf8 を使った方がよいです。
15201496これらの関数は不正なバイト列を扱う手段を提供し、一般的により親切な
15211497インターフェースを持ちます。
15221498
15231499=head2 Another Portable Binary Encoding
15241500
15251501(その他の移植性のあるバイナリエンコーディング)
15261502
15271503=begin original
15281504
15291505The pack code C<w> has been added to support a portable binary data
15301506encoding scheme that goes way beyond simple integers. (Details can
1531be found at L<https://github.com/mworks-project/mw_scarab/blob/master/Scarab-0.1.00d19/doc/binary-serialization.txt>,
1507be found at L<http://Casbah.org/>, the Scarab project.) A BER (Binary Encoded
1532the Scarab project.) A BER (Binary Encoded
15331508Representation) compressed unsigned integer stores base 128
15341509digits, most significant digit first, with as few digits as possible.
15351510Bit eight (the high bit) is set on each byte except the last. There
15361511is no size limit to BER encoding, but Perl won't go to extremes.
15371512
15381513=end original
15391514
15401515pack コード C<w> は、単純な整数とは程遠い、移植性のある
15411516バイナリデータエンコーディングスキームに対応するために追加されました。
1542(詳細については Scarab プロジェクト
1517(詳細については Scarab プロジェクト L<http://Casbah.org/> にあります。)
1543L<https://github.com/mworks-project/mw_scarab/blob/master/Scarab-0.1.00d19/doc/binary-serialization.txt>
1544にあります。)
15451518BER (Binary Encoded Representation) 圧縮符号なし整数は 128 を基数として、
15461519最上位ビットを最初にして、可能な限り少ない桁になるように保管します。
15471520ビット 8 (最上位ビット) は、最後以外のバイトでセットされます。
15481521BER エンコーディングにはサイズ制限がありませんが、Perl は極端なことは
15491522しません。
15501523
15511524 my $berbuf = pack( 'w*', 1, 128, 128+1, 128*128+127 );
15521525
15531526=begin original
15541527
15551528A hex dump of C<$berbuf>, with spaces inserted at the right places,
15561529shows 01 8100 8101 81807F. Since the last byte is always less than
15571530128, C<unpack> knows where to stop.
15581531
15591532=end original
15601533
15611534C<$berbuf> を、適切な位置に空白を入れつつ 16 進ダンプを取ると、
1562153501 8100 8101 81807F となります。
15631536最後のバイトは常に 128 より小さくなるので、C<unpack> は停止する位置が
15641537わかります。
15651538
15661539=head1 Template Grouping
15671540
15681541(テンプレートのグループ化)
15691542
15701543=begin original
15711544
15721545Prior to Perl 5.8, repetitions of templates had to be made by
15731546C<x>-multiplication of template strings. Now there is a better way as
15741547we may use the pack codes C<(> and C<)> combined with a repeat count.
15751548The C<unpack> template from the Stack Frame example can simply
15761549be written like this:
15771550
15781551=end original
15791552
15801553Perl 5.8 以前では、テンプレートの繰り返しはテンプレート文字列を C<x> 回
15811554繰り返すことで作る必要がありました。
15821555今では、pack コード C<(> と C<)> に繰り返し数を組み合わせて使うという
15831556よりよい方法があります。
15841557スタックフレームの例の C<unpack> テンプレートは単に以下のように書けます:
15851558
15861559 unpack( 'v2 (vXXCC)5 v5', $frame )
15871560
15881561=begin original
15891562
15901563Let's explore this feature a little more. We'll begin with the equivalent of
15911564
15921565=end original
15931566
15941567この機能についてもうすこしだけ探求してみましょう。
15951568以下と等価なものから始めます:
15961569
15971570 join( '', map( substr( $_, 0, 1 ), @str ) )
15981571
15991572=begin original
16001573
16011574which returns a string consisting of the first character from each string.
16021575Using pack, we can write
16031576
16041577=end original
16051578
16061579これは、それぞれの文字列の最初の文字からなる文字列を返します。
16071580pack を使うと、以下のように書けます:
16081581
16091582 pack( '(A)'.@str, @str )
16101583
16111584=begin original
16121585
16131586or, because a repeat count C<*> means "repeat as often as required",
16141587simply
16151588
16161589=end original
16171590
16181591あるいは、繰り返し数 C<*> は「必要なだけ繰り返す」ことを意味するので、
16191592単に以下のようになります:
16201593
16211594 pack( '(A)*', @str )
16221595
16231596=begin original
16241597
16251598(Note that the template C<A*> would only have packed C<$str[0]> in full
16261599length.)
16271600
16281601=end original
16291602
16301603(テンプレートは C<A*> は C<$str[0]> を 完全な長さで pack するだけという
16311604ことに注意してください。)
16321605
16331606=begin original
16341607
16351608To pack dates stored as triplets ( day, month, year ) in an array C<@dates>
16361609into a sequence of byte, byte, short integer we can write
16371610
16381611=end original
16391612
16401613配列 C<@dates> に 3 つ組 (日、月、年) として保管されている日付を
16411614バイト、バイト、short に pack するには、以下のように書きます
16421615
16431616 $pd = pack( '(CCS)*', map( @$_, @dates ) );
16441617
16451618=begin original
16461619
16471620To swap pairs of characters in a string (with even length) one could use
16481621several techniques. First, let's use C<x> and C<X> to skip forward and back:
16491622
16501623=end original
16511624
16521625ある文字列の中の(同じ長さの)部分文字列の組を交換するには、いくつかの
16531626技が使えます。
16541627まず、読み飛ばして戻ってくるために C<x> と C<X> を使いましょう:
16551628
16561629 $s = pack( '(A)*', unpack( '(xAXXAx)*', $s ) );
16571630
16581631=begin original
16591632
16601633We can also use C<@> to jump to an offset, with 0 being the position where
16611634we were when the last C<(> was encountered:
16621635
16631636=end original
16641637
16651638また、オフセットに飛ぶために C<@> も使えます; ここで 0 は最後に C<(> に
16661639遭遇した位置になります:
16671640
16681641 $s = pack( '(A)*', unpack( '(@1A @0A @2)*', $s ) );
16691642
16701643=begin original
16711644
16721645Finally, there is also an entirely different approach by unpacking big
16731646endian shorts and packing them in the reverse byte order:
16741647
16751648=end original
16761649
16771650最後に、ビッグエンディアンの short として unpack して、逆のバイト順で
16781651pack するという、全く異なった手法もあります:
16791652
16801653 $s = pack( '(v)*', unpack( '(n)*', $s );
16811654
16821655=head1 Lengths and Widths
16831656
16841657(長さと幅)
16851658
16861659=head2 String Lengths
16871660
16881661(文字列の長さ)
16891662
16901663=begin original
16911664
16921665In the previous section we've seen a network message that was constructed
16931666by prefixing the binary message length to the actual message. You'll find
16941667that packing a length followed by so many bytes of data is a
16951668frequently used recipe since appending a null byte won't work
16961669if a null byte may be part of the data. Here is an example where both
16971670techniques are used: after two null terminated strings with source and
16981671destination address, a Short Message (to a mobile phone) is sent after
16991672a length byte:
17001673
17011674=end original
17021675
17031676前の章で、実際のメッセージの前にメッセージの長さをバイナリで前置することで
17041677構成されたネットワークメッセージを見ました。
17051678NUL バイトを追加するという方法は、データの一部として NUL バイトが
17061679含まれているときには動作しないので、引き続くデータの長さを pack するという
17071680方法はよく見られます。
17081681以下は両方の技術を使った例です: 送り元と送り先のアドレスを示す 2 つの
17091682NUL 終端文字列の後、(携帯電話への)ショートメッセージがその長さの後に
17101683送られます:
17111684
17121685 my $msg = pack( 'Z*Z*CA*', $src, $dst, length( $sm ), $sm );
17131686
17141687=begin original
17151688
17161689Unpacking this message can be done with the same template:
17171690
17181691=end original
17191692
17201693このメッセージを unpack するには同じテンプレートで可能です:
17211694
17221695 ( $src, $dst, $len, $sm ) = unpack( 'Z*Z*CA*', $msg );
17231696
17241697=begin original
17251698
17261699There's a subtle trap lurking in the offing: Adding another field after
17271700the Short Message (in variable C<$sm>) is all right when packing, but this
17281701cannot be unpacked naively:
17291702
17301703=end original
17311704
17321705遠くに微妙な罠が顔を覗かせています: (変数 C<$sm> に入っている)
17331706ショートメッセージの後にフィールドを追加すると、pack は問題ありませんが、
17341707ネイティブに unpack 出来なくなります。
17351708
17361709 # pack a message
17371710 my $msg = pack( 'Z*Z*CA*C', $src, $dst, length( $sm ), $sm, $prio );
17381711
17391712 # unpack fails - $prio remains undefined!
17401713 ( $src, $dst, $len, $sm, $prio ) = unpack( 'Z*Z*CA*C', $msg );
17411714
17421715=begin original
17431716
17441717The pack code C<A*> gobbles up all remaining bytes, and C<$prio> remains
17451718undefined! Before we let disappointment dampen the morale: Perl's got
17461719the trump card to make this trick too, just a little further up the sleeve.
17471720Watch this:
17481721
17491722=end original
17501723
17511724pack コード C<A*> は残り全てのコードを読み込んでしまい、C<$prio> が
17521725未定義のままになってしまうのです!
17531726がっかりして士気をくじかれる前に: Perl はこのようなトリックに対しても
17541727切り札を持っています; もう少し袖をまくってください。
17551728これを見てください:
17561729
17571730 # pack a message: ASCIIZ, ASCIIZ, length/string, byte
17581731 my $msg = pack( 'Z* Z* C/A* C', $src, $dst, $sm, $prio );
17591732
17601733 # unpack
17611734 ( $src, $dst, $sm, $prio ) = unpack( 'Z* Z* C/A* C', $msg );
17621735
17631736=begin original
17641737
17651738Combining two pack codes with a slash (C</>) associates them with a single
17661739value from the argument list. In C<pack>, the length of the argument is
17671740taken and packed according to the first code while the argument itself
17681741is added after being converted with the template code after the slash.
17691742This saves us the trouble of inserting the C<length> call, but it is
17701743in C<unpack> where we really score: The value of the length byte marks the
17711744end of the string to be taken from the buffer. Since this combination
17721745doesn't make sense except when the second pack code isn't C<a*>, C<A*>
17731746or C<Z*>, Perl won't let you.
17741747
17751748=end original
17761749
17771750二つの pack コードをスラッシュ (C</>) で繋ぐことで、引数リストの 1 つの
17781751値と結び付けられます。
17791752C<pack> では、引数の長さが取られて最初のコードに従って pack される一方、
17801753引数自体はスラッシュの後のテンプレートコードによって変換された後
17811754追加されます。
17821755これは C<length> 呼び出しを挿入することによるトラブルを救いますが、
17831756本当に効果があるのは C<unpack> においてです: 長さを示すバイトの値は
17841757バッファから取られる文字列の末尾をマークします。
17851758この組み合わせは 2 つ目の pack コードが C<a*>, C<A*>, C<Z*> でない場合
17861759以外は意味がないので、Perl はそうはさせません。
17871760
17881761=begin original
17891762
17901763The pack code preceding C</> may be anything that's fit to represent a
17911764number: All the numeric binary pack codes, and even text codes such as
17921765C<A4> or C<Z*>:
17931766
17941767=end original
17951768
17961769C</> の前に置く pack コードは、数値を表現するのに適したものであれば
17971770なんでも使えます:
17981771全ての数値バイナリ pack コードおよび、C<A4> や C<Z*> のような
17991772テキストコードにも対応します:
18001773
18011774 # pack/unpack a string preceded by its length in ASCII
18021775 my $buf = pack( 'A4/A*', "Humpty-Dumpty" );
18031776 # unpack $buf: '13 Humpty-Dumpty'
18041777 my $txt = unpack( 'A4/A*', $buf );
18051778
18061779=begin original
18071780
18081781C</> is not implemented in Perls before 5.6, so if your code is required to
1809work on ancient Perls you'll need to C<unpack( 'Z* Z* C')> to get the length,
1782work on older Perls you'll need to C<unpack( 'Z* Z* C')> to get the length,
18101783then use it to make a new unpack string. For example
18111784
18121785=end original
18131786
18141787C</> は 5.6 以前の Perl には実装されていないので、もし、より古い Perl で
18151788動作することが要求される場合は、長さを得るために C<unpack( 'Z* Z* C')> を
18161789使って、それから新しい unpack 文字列を作ってそれを使う必要があります。
18171790例えば:
18181791
1819 # pack a message: ASCIIZ, ASCIIZ, length, string, byte
1792 # pack a message: ASCIIZ, ASCIIZ, length, string, byte (5.005 compatible)
1820 # (5.005 compatible)
18211793 my $msg = pack( 'Z* Z* C A* C', $src, $dst, length $sm, $sm, $prio );
18221794
18231795 # unpack
18241796 ( undef, undef, $len) = unpack( 'Z* Z* C', $msg );
18251797 ($src, $dst, $sm, $prio) = unpack ( "Z* Z* x A$len C", $msg );
18261798
18271799=begin original
18281800
18291801But that second C<unpack> is rushing ahead. It isn't using a simple literal
18301802string for the template. So maybe we should introduce...
18311803
18321804=end original
18331805
18341806しかしこの 2 番目の C<unpack> は先走りました。
18351807これはテンプレートとして単純なリテラル文字列を使っていません。
18361808それでは説明するべきでしょう…
18371809
18381810=head2 Dynamic Templates
18391811
18401812(動的テンプレート)
18411813
18421814=begin original
18431815
18441816So far, we've seen literals used as templates. If the list of pack
18451817items doesn't have fixed length, an expression constructing the
18461818template is required (whenever, for some reason, C<()*> cannot be used).
18471819Here's an example: To store named string values in a way that can be
18481820conveniently parsed by a C program, we create a sequence of names and
18491821null terminated ASCII strings, with C<=> between the name and the value,
18501822followed by an additional delimiting null byte. Here's how:
18511823
18521824=end original
18531825
18541826これまでは、テンプレートとして使われるリテラルを見てきました。
18551827pack するアイテムのリストが固定長でない場合(何らかの理由で C<()*> が
18561828使えないなら)、テンプレートを構成する式が必要です。
18571829以下は例です: C プログラムで使いやすい形で名前付き文字列値を保管するために、
18581830一続きの名前と NUL 終端された ASCII 文字列を作ります;
18591831名前と値の間には C<=> を置いて、最後に追加のデリミタとなる NUL バイトを
18601832置きます。
18611833以下のようにします:
18621834
18631835 my $env = pack( '(A*A*Z*)' . keys( %Env ) . 'C',
18641836 map( { ( $_, '=', $Env{$_} ) } keys( %Env ) ), 0 );
18651837
18661838=begin original
18671839
18681840Let's examine the cogs of this byte mill, one by one. There's the C<map>
18691841call, creating the items we intend to stuff into the C<$env> buffer:
18701842to each key (in C<$_>) it adds the C<=> separator and the hash entry value.
18711843Each triplet is packed with the template code sequence C<A*A*Z*> that
18721844is repeated according to the number of keys. (Yes, that's what the C<keys>
18731845function returns in scalar context.) To get the very last null byte,
18741846we add a C<0> at the end of the C<pack> list, to be packed with C<C>.
18751847(Attentive readers may have noticed that we could have omitted the 0.)
18761848
18771849=end original
18781850
18791851このバイト処理機の要素を一つ一つ調査してみましょう。
18801852C<map> 呼び出しは、C<$env> バッファに入れることを想定している内容の
18811853アイテムを作成します:
18821854(C<$_> の) それぞれのキーについて、C<=> セパレータとハッシュエントリの値を
18831855追加します。
18841856それぞれの 3 つ組は、キーの数
18851857(はい、これは C<keys> 関数がスカラコンテキストで返すものです。)
18861858に従って繰り返されるテンプレートコードの
18871859並び C<A*A*Z*> で pack されます。
18881860まさに最後の NUL バイトを得るために、C<pack> リストの最後に C<C> で
18891861pack するための C<0> を追加します。
18901862(注意深い読者なら、この 0 は省略できることに気付いたかもしれません。)
18911863
18921864=begin original
18931865
18941866For the reverse operation, we'll have to determine the number of items
18951867in the buffer before we can let C<unpack> rip it apart:
18961868
18971869=end original
18981870
18991871逆操作のために、C<unpack> に分解させる前にバッファにあるアイテムの数を
19001872決定する必要があります:
19011873
19021874 my $n = $env =~ tr/\0// - 1;
19031875 my %env = map( split( /=/, $_ ), unpack( "(Z*)$n", $env ) );
19041876
19051877=begin original
19061878
19071879The C<tr> counts the null bytes. The C<unpack> call returns a list of
19081880name-value pairs each of which is taken apart in the C<map> block.
19091881
19101882=end original
19111883
19121884C<tr> はヌルバイトを数えます。
19131885C<unpack> 呼び出しは名前-値の組のリストを返し、そのそれぞれが
19141886C<map> ブロックで分割されます。
19151887
19161888=head2 Counting Repetitions
19171889
19181890(繰り返しを数える)
19191891
19201892=begin original
19211893
19221894Rather than storing a sentinel at the end of a data item (or a list of items),
19231895we could precede the data with a count. Again, we pack keys and values of
19241896a hash, preceding each with an unsigned short length count, and up front
19251897we store the number of pairs:
19261898
19271899=end original
19281900
19291901データアイテム(あるいはアイテムのリスト)の最後に見張りをおくのではなく、
19301902データの数を先においておくこともできます。
19311903再び、ハッシュのキーと値を pack します; それぞれの前には符号なし short で
19321904長さが置かれ、先頭には組の数を保管します:
19331905
19341906 my $env = pack( 'S(S/A* S/A*)*', scalar keys( %Env ), %Env );
19351907
19361908=begin original
19371909
19381910This simplifies the reverse operation as the number of repetitions can be
19391911unpacked with the C</> code:
19401912
19411913=end original
19421914
19431915繰り返し数は C</> コードで unpack できるので、逆操作は単純になります:
19441916
19451917 my %env = unpack( 'S/(S/A* S/A*)', $env );
19461918
19471919=begin original
19481920
19491921Note that this is one of the rare cases where you cannot use the same
19501922template for C<pack> and C<unpack> because C<pack> can't determine
19511923a repeat count for a C<()>-group.
19521924
19531925=end original
19541926
19551927これは、C<pack> は C<()> グループの繰り返し数を決定できないので、
19561928C<pack> と C<unpack> で同じテンプレートが使えない珍しい場合であることに
19571929注意してください。
19581930
1959=head2 Intel HEX
1960
1961=begin original
1962
1963Intel HEX is a file format for representing binary data, mostly for
1964programming various chips, as a text file. (See
1965L<https://en.wikipedia.org/wiki/.hex> for a detailed description, and
1966L<https://en.wikipedia.org/wiki/SREC_(file_format)> for the Motorola
1967S-record format, which can be unravelled using the same technique.)
1968Each line begins with a colon (':') and is followed by a sequence of
1969hexadecimal characters, specifying a byte count I<n> (8 bit),
1970an address (16 bit, big endian), a record type (8 bit), I<n> data bytes
1971and a checksum (8 bit) computed as the least significant byte of the two's
1972complement sum of the preceding bytes. Example: C<:0300300002337A1E>.
1973
1974=end original
1975
1976Intel HEX バイナリデータを表現するためのファイル形式で、ほとんどの場合
1977様々なデータをテキストファイルとしてプログラミングするためのものです。
1978(詳細な記述については L<https://en.wikipedia.org/wiki/.hex> を、
1979同じテクニックを使って展開できる Motorola S-record 形式については
1980L<https://en.wikipedia.org/wiki/SREC_(file_format)> を参照してください。)
1981それぞれの行はコロン (':') で始まり、バイトカウント I<n> (8 ビット)、
1982アドレス (16 ビット、ビッグエンディアン)、レコード型 (8 ビット)、
1983I<n> バイトのデータ、そこまでのバイト列の合計の最下位バイトの 2 の補数で
1984表されるチェックサム (8 ビット)、からなる 16 進文字の並びが続きます。
1985例: C<:0300300002337A1E>。
1986
1987=begin original
1988
1989The first step of processing such a line is the conversion, to binary,
1990of the hexadecimal data, to obtain the four fields, while checking the
1991checksum. No surprise here: we'll start with a simple C<pack> call to
1992convert everything to binary:
1993
1994=end original
1995
1996このような行を処理するための最初のステップは、四つのフィールドを得るために
199716 進データをバイナリに変換して、チェックサムを調べることです。
1998ここには驚きはありません: 全てをバイナリに変換するための単純な
1999C<pack> 呼び出しから始めます:
2000
2001 my $binrec = pack( 'H*', substr( $hexrec, 1 ) );
2002
2003=begin original
2004
2005The resulting byte sequence is most convenient for checking the checksum.
2006Don't slow your program down with a for loop adding the C<ord> values
2007of this string's bytes - the C<unpack> code C<%> is the thing to use
2008for computing the 8-bit sum of all bytes, which must be equal to zero:
2009
2010=end original
2011
2012結果のバイト並びははチェックサムを計算するのに最も便利です。
2013この文字列のバイトの C<ord> の値を加算するループでプログラムの速度を
2014落とすようなことをしないでください - C<unpack> の C<%> コードは
2015全てのバイトの 8 ビットの合計を計算するためのもので、これは 0 でなければ
2016なりません:
2017
2018 die unless unpack( "%8C*", $binrec ) == 0;
2019
2020=begin original
2021
2022Finally, let's get those four fields. By now, you shouldn't have any
2023problems with the first three fields - but how can we use the byte count
2024of the data in the first field as a length for the data field? Here
2025the codes C<x> and C<X> come to the rescue, as they permit jumping
2026back and forth in the string to unpack.
2027
2028=end original
2029
2030最後に、四つのフィールドを取り出しましょう。
2031ここまでで、最初の三つのフィールドを取り出すのには何の問題もないはずです -
2032しかし最初のフィールドにあるデータのバイトカウントをデータフィールドの
2033長さに使うにはどうすればいいでしょう?
2034ここで C<x> と C<X> が助けにやってきて、戻って文字列の 4 番目を
2035unpack できるようにします。
2036
2037 my( $addr, $type, $data ) = unpack( "x n C X4 C x3 /a", $bin );
2038
2039=begin original
2040
2041Code C<x> skips a byte, since we don't need the count yet. Code C<n> takes
2042care of the 16-bit big-endian integer address, and C<C> unpacks the
2043record type. Being at offset 4, where the data begins, we need the count.
2044C<X4> brings us back to square one, which is the byte at offset 0.
2045Now we pick up the count, and zoom forth to offset 4, where we are
2046now fully furnished to extract the exact number of data bytes, leaving
2047the trailing checksum byte alone.
2048
2049=end original
2050
2051C<x> コードは、まだカウントは必要ではないので 1 バイト飛ばします。
2052C<n> コードは 16 ビットビッグエンディアン整数アドレスを取得し、
2053C<C> はレコード型を unpack します。
2054データが始まる位置であるオフセット 4 に来て、カウントが必要です。
2055C<X4> は 1 マス目、つまりオフセット 0 のバイトに戻ります。
2056ここでカウントを取りだして、正確な数のデータを展開するために提供されている
2057オフセット 4 に移動して、末尾のチェックサムバイトだけを残します。
2058
20591931=head1 Packing and Unpacking C Structures
20601932
20611933(C の構造体を pack/unpack する)
20621934
20631935=begin original
20641936
20651937In previous sections we have seen how to pack numbers and character
20661938strings. If it were not for a couple of snags we could conclude this
20671939section right away with the terse remark that C structures don't
20681940contain anything else, and therefore you already know all there is to it.
20691941Sorry, no: read on, please.
20701942
20711943=end original
20721944
20731945前のセクションで、数値と文字列を pack する方法を見ました。
20741946もしここに障害がないなら、「C 構造体には他に何もなく、従ってあなたは
2075既に C 構造体を pack/unpack するための全てを知っています」
1947既に C 構造体を pack/unpack するための全てを知っています
20761948という簡潔な見解と共にこの章をすぐに締めくくることができます。
20771949すみません、そうではありません: どうか読み進めてください。
20781950
20791951=begin original
20801952
20811953If you have to deal with a lot of C structures, and don't want to
20821954hack all your template strings manually, you'll probably want to have
20831955a look at the CPAN module C<Convert::Binary::C>. Not only can it parse
20841956your C source directly, but it also has built-in support for all the
20851957odds and ends described further on in this section.
20861958
20871959=end original
20881960
20891961もし大量の C 構造体を扱う必要があって、全てのテンプレート文字列を手動で
20901962ハックしたくないなら、おそらく一度 CPAN モジュール C<Convert::Binary::C> を
20911963見たほうが良いでしょう。
20921964C ソースを直接パースできるだけでなく、この章でさらに記述される全ての
20931965雑務に対する組み込みのサポートがあります。
20941966
20951967=head2 The Alignment Pit
20961968
20971969(アライメントの落とし穴)
20981970
20991971=begin original
21001972
21011973In the consideration of speed against memory requirements the balance
21021974has been tilted in favor of faster execution. This has influenced the
21031975way C compilers allocate memory for structures: On architectures
21041976where a 16-bit or 32-bit operand can be moved faster between places in
21051977memory, or to or from a CPU register, if it is aligned at an even or
21061978multiple-of-four or even at a multiple-of eight address, a C compiler
21071979will give you this speed benefit by stuffing extra bytes into structures.
21081980If you don't cross the C shoreline this is not likely to cause you any
21091981grief (although you should care when you design large data structures,
21101982or you want your code to be portable between architectures (you do want
21111983that, don't you?)).
21121984
21131985=end original
21141986
21151987速度とメモリ消費のバランスは、より速く実行できる方に傾いています。
21161988これは C コンパイラが構造体のためにメモリを割り当てる方法に影響します:
21171989偶数、4 の倍数、あるいは 8 の倍数のアドレスにアライメントされていれば、
2118199016 ビットや 32 ビットのオペランドや CPU レジスタへの出し入れが速くなる
21191991アーキテクチャでは、C コンパイラは構造体に追加のバイトを入れることで
21201992この速度メリットを受けるようにします。
21211993もし C の海岸線を越えないのなら、これがなんらかの面倒を引き起こすことは
21221994ありそうにありません (しかし、大きなデータ構造を設計したり、
21231995アーキテクチャ間で移植性のあるコードがほしい場合(そうしたくないですか?)、
2124気にするべきです)。
1996気にするべきです)。
21251997
21261998=begin original
21271999
21282000To see how this affects C<pack> and C<unpack>, we'll compare these two
21292001C structures:
21302002
21312003=end original
21322004
21332005これが C<pack> と C<unpack> にどのように影響を与えるかを見るために、
21342006これら 2 つの C 構造体を比較してみます:
21352007
21362008 typedef struct {
21372009 char c1;
21382010 short s;
21392011 char c2;
21402012 long l;
21412013 } gappy_t;
21422014
21432015 typedef struct {
21442016 long l;
21452017 short s;
21462018 char c1;
21472019 char c2;
21482020 } dense_t;
21492021
21502022=begin original
21512023
21522024Typically, a C compiler allocates 12 bytes to a C<gappy_t> variable, but
21532025requires only 8 bytes for a C<dense_t>. After investigating this further,
21542026we can draw memory maps, showing where the extra 4 bytes are hidden:
21552027
21562028=end original
21572029
21582030典型的には、C コンパイラは C<gappy_t> 変数には 12 バイトを割り当てますが、
21592031C<dense_t> には 8 バイトしか割り当てません。
21602032これをさらに調査した後、余分な 4 バイトが隠れていることが分かる
21612033メモリマップが書けます:
21622034
21632035 0 +4 +8 +12
21642036 +--+--+--+--+--+--+--+--+--+--+--+--+
21652037 |c1|xx| s |c2|xx|xx|xx| l | xx = fill byte
21662038 +--+--+--+--+--+--+--+--+--+--+--+--+
21672039 gappy_t
21682040
21692041 0 +4 +8
21702042 +--+--+--+--+--+--+--+--+
21712043 | l | h |c1|c2|
21722044 +--+--+--+--+--+--+--+--+
21732045 dense_t
21742046
21752047=begin original
21762048
21772049And that's where the first quirk strikes: C<pack> and C<unpack>
21782050templates have to be stuffed with C<x> codes to get those extra fill bytes.
21792051
21802052=end original
21812053
21822054そしてこれが最初の思いがけない一撃の理由です:
21832055C<pack> と C<unpack> のテンプレートは、これらの余分に埋めるバイトのために
21842056C<X> コードを詰める必要があります。
21852057
21862058=begin original
21872059
21882060The natural question: "Why can't Perl compensate for the gaps?" warrants
21892061an answer. One good reason is that C compilers might provide (non-ANSI)
21902062extensions permitting all sorts of fancy control over the way structures
21912063are aligned, even at the level of an individual structure field. And, if
21922064this were not enough, there is an insidious thing called C<union> where
21932065the amount of fill bytes cannot be derived from the alignment of the next
21942066item alone.
21952067
21962068=end original
21972069
21982070自然な質問: 「なぜ Perl は隙間を埋め合わせられないの?」には答えるのが
21992071当然です。
22002072一つのよい理由は、個々の構造体フィールドのレベルでさえ、構造体の
22012073アライメント方法のあらゆる種類の制御方法を許している(非 ANSI の)拡張を
22022074提供しているCコンパイラがあるからです。
22032075そして、もしこれが十分でないなら、埋めるバイト数が次のアイテムの
22042076アライメントだけでは決定されない、C<union> と呼ばれる
22052077陰険なものがあります。
22062078
22072079=begin original
22082080
22092081OK, so let's bite the bullet. Here's one way to get the alignment right
22102082by inserting template codes C<x>, which don't take a corresponding item
22112083from the list:
22122084
22132085=end original
22142086
22152087よし、では困難に耐えましょう。
22162088これは、リストから対応する要素を使わないテンプレートコード C<x> を
22172089挿入することでアライメントを正しくする一つの方法です:
22182090
22192091 my $gappy = pack( 'cxs cxxx l!', $c1, $s, $c2, $l );
22202092
22212093=begin original
22222094
22232095Note the C<!> after C<l>: We want to make sure that we pack a long
22242096integer as it is compiled by our C compiler. And even now, it will only
22252097work for the platforms where the compiler aligns things as above.
22262098And somebody somewhere has a platform where it doesn't.
22272099[Probably a Cray, where C<short>s, C<int>s and C<long>s are all 8 bytes. :-)]
22282100
22292101=end original
22302102
22312103C<l> の後の C<!> に注意してください: long 整数を C コンパイラで
22322104コンパイルされるのと同じ形になるのを確実にしたいです。
22332105そしてこの時点でも、これはコンパイラが上述のようにアライメントする
22342106プラットフォームでのみ動作します。
22352107そしてどこかの誰かはそうでないプラットフォームを使っています。
22362108[おそらくは、Cray です; これは C<short>, C<int>, C<long> が全て
223721098 バイトです。:-)]
22382110
22392111=begin original
22402112
22412113Counting bytes and watching alignments in lengthy structures is bound to
22422114be a drag. Isn't there a way we can create the template with a simple
22432115program? Here's a C program that does the trick:
22442116
22452117=end original
22462118
22472119とても長い構造体のバイト数を数えてアライメントを監視するのは面倒なことです。
22482120単純なプログラムでテンプレートを作る方法はないでしょうか?
22492121以下は技を使った C プログラムです:
22502122
22512123 #include <stdio.h>
22522124 #include <stddef.h>
22532125
22542126 typedef struct {
22552127 char fc1;
22562128 short fs;
22572129 char fc2;
22582130 long fl;
22592131 } gappy_t;
22602132
22612133 #define Pt(struct,field,tchar) \
22622134 printf( "@%d%s ", offsetof(struct,field), # tchar );
22632135
22642136 int main() {
22652137 Pt( gappy_t, fc1, c );
22662138 Pt( gappy_t, fs, s! );
22672139 Pt( gappy_t, fc2, c );
22682140 Pt( gappy_t, fl, l! );
22692141 printf( "\n" );
22702142 }
22712143
22722144=begin original
22732145
22742146The output line can be used as a template in a C<pack> or C<unpack> call:
22752147
22762148=end original
22772149
22782150出力行は C<pack> や C<unpack> 呼び出しのテンプレートとして使えます。
22792151
22802152 my $gappy = pack( '@0c @2s! @4c @8l!', $c1, $s, $c2, $l );
22812153
22822154=begin original
22832155
22842156Gee, yet another template code - as if we hadn't plenty. But
22852157C<@> saves our day by enabling us to specify the offset from the beginning
22862158of the pack buffer to the next item: This is just the value
22872159the C<offsetof> macro (defined in C<E<lt>stddef.hE<gt>>) returns when
22882160given a C<struct> type and one of its field names ("member-designator" in
22892161C standardese).
22902162
22912163=end original
22922164
22932165げー、新しいテンプレートコードです - まだ十分ではありませんでした。
22942166しかし C<@> は次のアイテムのための pack バッファの先頭からのオフセットを
22952167指定できるようにすることで手間を省きます:
22962168これは単に、C<struct> 型とそのフィールド名(C 標準での「メンバ指定子」)を
22972169与えたときに (C<E<lt>stddef.hE<gt>> で定義されている)C<offsetof> マクロが
22982170返す値です。
22992171
23002172=begin original
23012173
23022174Neither using offsets nor adding C<x>'s to bridge the gaps is satisfactory.
23032175(Just imagine what happens if the structure changes.) What we really need
23042176is a way of saying "skip as many bytes as required to the next multiple of N".
2305In fluent templates, you say this with C<x!N> where N is replaced by the
2177In fluent Templatese, you say this with C<x!N> where N is replaced by the
23062178appropriate value. Here's the next version of our struct packaging:
23072179
23082180=end original
23092181
23102182オフセットを使ったり、隙間を渡すために C<x> を追加することでは
23112183十分ではありません。
23122184(構造体が変更されたときに何が起こるかを単に想像してみてください。)
23132185本当に必要なものは、「次の N の倍数のバイトになるまでスキップする」と
23142186書く各方法です。
23152187雄弁なテンプレートでは、これは C<x!N> とできます (ここで N は適切な値
23162188に置き換えられます)。
23172189これは構造体のパッケージ化の次のバージョンです:
23182190
23192191 my $gappy = pack( 'c x!2 s c x!4 l!', $c1, $s, $c2, $l );
23202192
23212193=begin original
23222194
23232195That's certainly better, but we still have to know how long all the
23242196integers are, and portability is far away. Rather than C<2>,
23252197for instance, we want to say "however long a short is". But this can be
23262198done by enclosing the appropriate pack code in brackets: C<[s]>. So, here's
23272199the very best we can do:
23282200
23292201=end original
23302202
23312203これは確実により良いものですが、未だに全ての整数の長さを知る必要があり、
23322204移植性とはかけ離れています。
23332205例えば、C<2> の代わりに、「とにかく short の長さ」と書きたいです。
23342206しかし、これは適切な pack コードを大かっこで囲むこと (C<[s]>) で
23352207可能です。
23362208それで、これはできる限り最良のものです:
23372209
23382210 my $gappy = pack( 'c x![s] s c x![l!] l!', $c1, $s, $c2, $l );
23392211
23402212=head2 Dealing with Endian-ness
23412213
23422214(エンディアンを扱う)
23432215
23442216=begin original
23452217
23462218Now, imagine that we want to pack the data for a machine with a
23472219different byte-order. First, we'll have to figure out how big the data
23482220types on the target machine really are. Let's assume that the longs are
2349222132 bits wide and the shorts are 16 bits wide. You can then rewrite the
23502222template as:
23512223
23522224=end original
23532225
23542226ここで、異なるバイト順のマシンのためのデータを pack したいとします。
23552227まず、ターゲットマシンでの実際のデータ型の大きさを知る必要があります。
23562228long は 32 ビット幅で short が 16 ビット幅と仮定しましょう。
23572229ここでテンプレートは以下のように書き換えられます:
23582230
23592231 my $gappy = pack( 'c x![s] s c x![l] l', $c1, $s, $c2, $l );
23602232
23612233=begin original
23622234
23632235If the target machine is little-endian, we could write:
23642236
23652237=end original
23662238
23672239もしターゲットマシンがリトルエンディアンなら、以下のように書けます:
23682240
23692241 my $gappy = pack( 'c x![s] s< c x![l] l<', $c1, $s, $c2, $l );
23702242
23712243=begin original
23722244
23732245This forces the short and the long members to be little-endian, and is
23742246just fine if you don't have too many struct members. But we could also
23752247use the byte-order modifier on a group and write the following:
23762248
23772249=end original
23782250
23792251これは short と long のメンバをリトルエンディアンに強制し、もし
23802252あまり多くの構造体メンバがない場合は十分です。
23812253しかし、グループにバイト順修飾子を使うことも出来、以下のように書けます:
23822254
23832255 my $gappy = pack( '( c x![s] s c x![l] l )<', $c1, $s, $c2, $l );
23842256
23852257=begin original
23862258
23872259This is not as short as before, but it makes it more obvious that we
23882260intend to have little-endian byte-order for a whole group, not only
23892261for individual template codes. It can also be more readable and easier
23902262to maintain.
23912263
23922264=end original
23932265
23942266これは以前ほど短くありませんが、ここのテンプレートだけでなく、グループ全体に
23952267リトルエンディアンのバイト順を意図していることがより明らかです。
23962268これはまたより読みやすく、管理もより簡単です。
23972269
23982270=head2 Alignment, Take 2
23992271
24002272(アライメント、第二幕)
24012273
24022274=begin original
24032275
24042276I'm afraid that we're not quite through with the alignment catch yet. The
24052277hydra raises another ugly head when you pack arrays of structures:
24062278
24072279=end original
24082280
24092281アライメントの捕捉について、十分に説明していないのではないかと
24102282心配しています。
24112283構造体の配列を pack しようとすると、ヒドラはまた別の醜い頭をもたげてきます。
24122284
24132285 typedef struct {
24142286 short count;
24152287 char glyph;
24162288 } cell_t;
24172289
24182290 typedef cell_t buffer_t[BUFLEN];
24192291
24202292=begin original
24212293
24222294Where's the catch? Padding is neither required before the first field C<count>,
24232295nor between this and the next field C<glyph>, so why can't we simply pack
24242296like this:
24252297
24262298=end original
24272299
24282300どこに罠があるのでしょう?
24292301最初のフィールド C<count> の前や、これと次のフィールド C<glyph> の間に
24302302パッディングは不要です; それならなぜ以下のように簡単に
24312303pack できないのでしょう:
24322304
24332305 # something goes wrong here:
24342306 pack( 's!a' x @buffer,
24352307 map{ ( $_->{count}, $_->{glyph} ) } @buffer );
24362308
24372309=begin original
24382310
24392311This packs C<3*@buffer> bytes, but it turns out that the size of
24402312C<buffer_t> is four times C<BUFLEN>! The moral of the story is that
24412313the required alignment of a structure or array is propagated to the
24422314next higher level where we have to consider padding I<at the end>
24432315of each component as well. Thus the correct template is:
24442316
24452317=end original
24462318
24472319これは C<3*@buffer> バイトに pack しますが、C<buffer_t> のサイズは
24482320C<BUFLEN> の 4 倍になるのです!
24492321このお話の教訓は、構造体や配列で必要なアライメントは、それぞれの要素の
24502322I<最後に> パッディングを考慮する必要がある場所で、より高いレベルに
24512323伝播するということです。
24522324従って、正しいテンプレートは:
24532325
24542326 pack( 's!ax' x @buffer,
24552327 map{ ( $_->{count}, $_->{glyph} ) } @buffer );
24562328
24572329=head2 Alignment, Take 3
24582330
24592331(アライメント、第三幕)
24602332
24612333=begin original
24622334
24632335And even if you take all the above into account, ANSI still lets this:
24642336
24652337=end original
24662338
24672339上記のことを全て頭に入れたとしても、ANSI は以下のような場合:
24682340
24692341 typedef struct {
24702342 char foo[2];
24712343 } foo_t;
24722344
24732345=begin original
24742346
24752347vary in size. The alignment constraint of the structure can be greater than
24762348any of its elements. [And if you think that this doesn't affect anything
24772349common, dismember the next cellphone that you see. Many have ARM cores, and
24782350the ARM structure rules make C<sizeof (foo_t)> == 4]
24792351
24802352=end original
24812353
24822354サイズは様々であるとしています。
24832355構造のアライメント制約は、それぞれの要素よりも大きいかもしれません。
24842356[そしてもしこれが一般的には何も影響を与えないと考えているなら、
24852357次に見た携帯電話を分解してみてください。
24862358多くは ARM コアを使っていて、ARM 構造体ルールでは
24872359C<sizeof (foo_t)> == 4 となります]
24882360
24892361=head2 Pointers for How to Use Them
24902362
24912363(ポインタをどう扱うかのポインタ)
24922364
24932365=begin original
24942366
24952367The title of this section indicates the second problem you may run into
24962368sooner or later when you pack C structures. If the function you intend
24972369to call expects a, say, C<void *> value, you I<cannot> simply take
24982370a reference to a Perl variable. (Although that value certainly is a
24992371memory address, it's not the address where the variable's contents are
25002372stored.)
25012373
25022374=end original
25032375
25042376この章のタイトルは、C の構造体を pack するときに遅かれ早かれ出会うことになる
250523772 番目の問題を指し示しています。
25062378呼び出そうとしている関数が、例えば、C<void *> の値を想定している場合、
25072379単純に Perl の変数のリファレンスを使うことは I<できません>。
25082380(確かに値はメモリアドレスですが、値の内容が保持されているアドレスでは
25092381ないからです。)
25102382
25112383=begin original
25122384
25132385Template code C<P> promises to pack a "pointer to a fixed length string".
25142386Isn't this what we want? Let's try:
25152387
25162388=end original
25172389
25182390テンプレートコード C<P> は、「固定長文字列へのポインタ」を pack することを
25192391約束します。
25202392これが望みのものではないですか?
25212393試してみましょう:
25222394
25232395 # allocate some storage and pack a pointer to it
25242396 my $memory = "\x00" x $size;
25252397 my $memptr = pack( 'P', $memory );
25262398
25272399=begin original
25282400
25292401But wait: doesn't C<pack> just return a sequence of bytes? How can we pass this
25302402string of bytes to some C code expecting a pointer which is, after all,
25312403nothing but a number? The answer is simple: We have to obtain the numeric
25322404address from the bytes returned by C<pack>.
25332405
25342406=end original
25352407
25362408ちょっと待った: C<pack> は単にバイトシーケンスを返すのでは?
25372409どうやってこのバイトの文字列を、ポインタ、つまり結局は数値でしかないものを
25382410想定している C のコードに渡せるのでしょう?
25392411答えは単純です: C<pack> で返されたバイト列から数値のアドレスを得なければ
25402412なりません。
25412413
25422414 my $ptr = unpack( 'L!', $memptr );
25432415
25442416=begin original
25452417
25462418Obviously this assumes that it is possible to typecast a pointer
25472419to an unsigned long and vice versa, which frequently works but should not
25482420be taken as a universal law. - Now that we have this pointer the next question
25492421is: How can we put it to good use? We need a call to some C function
25502422where a pointer is expected. The read(2) system call comes to mind:
25512423
25522424=end original
25532425
25542426明らかに、これはポインタから unsigned long への、およびその逆の型キャストが
25552427可能であることを仮定しています; これはしばしば動作しますが、普遍的な
25562428原則として扱うべきではありません。
25572429- ここでこのポインタを得ましたが、次の質問は: これをうまく使うには
25582430どうするのがよいでしょう?
25592431ポインタを想定している C 関数を呼び出す必要があります。
25602432read(2) システムコールが心に浮かびます:
25612433
25622434 ssize_t read(int fd, void *buf, size_t count);
25632435
25642436=begin original
25652437
25662438After reading L<perlfunc> explaining how to use C<syscall> we can write
25672439this Perl function copying a file to standard output:
25682440
25692441=end original
25702442
25712443L<perlfunc> にある C<syscall> の使い方の説明を読んだ後、ファイルを
25722444標準出力にコピーする Perl 関数を書けます:
25732445
2574 require 'syscall.ph'; # run h2ph to generate this file
2446 require 'syscall.ph';
25752447 sub cat($){
25762448 my $path = shift();
25772449 my $size = -s $path;
25782450 my $memory = "\x00" x $size; # allocate some memory
25792451 my $ptr = unpack( 'L', pack( 'P', $memory ) );
25802452 open( F, $path ) || die( "$path: cannot open ($!)\n" );
25812453 my $fd = fileno(F);
25822454 my $res = syscall( &SYS_read, fileno(F), $ptr, $size );
25832455 print $memory;
25842456 close( F );
25852457 }
25862458
25872459=begin original
25882460
25892461This is neither a specimen of simplicity nor a paragon of portability but
25902462it illustrates the point: We are able to sneak behind the scenes and
25912463access Perl's otherwise well-guarded memory! (Important note: Perl's
25922464C<syscall> does I<not> require you to construct pointers in this roundabout
25932465way. You simply pass a string variable, and Perl forwards the address.)
25942466
25952467=end original
25962468
25972469これは単純さの見本でもなければ移植性の模範でもありませんが、要点を
25982470示しています: 舞台裏に忍び込んで、その他の点では良く守られている Perl の
25992471メモリにアクセスできます!
26002472(重要な注意: Perl の C<syscall> は、この回りくどい方法でポインタを
26012473構成する必要は I<ありません> 。
26022474単に文字列変数を渡せば、Perl がアドレスを転送します。)
26032475
26042476=begin original
26052477
26062478How does C<unpack> with C<P> work? Imagine some pointer in the buffer
26072479about to be unpacked: If it isn't the null pointer (which will smartly
26082480produce the C<undef> value) we have a start address - but then what?
26092481Perl has no way of knowing how long this "fixed length string" is, so
26102482it's up to you to specify the actual size as an explicit length after C<P>.
26112483
26122484=end original
26132485
26142486C<unpack> では C<P> はどのように動作するのでしょう?
26152487unpack されようとしているバッファにあるポインタを想像します:
26162488もしそれが(賢く C<undef> 値を生成する)ヌルポインタでない場合、開始アドレスを
26172489得ることになります - でも、それで?
26182490Perl はこの「固定長文字列」の長さを知る方法がないので、C<P> の後ろに
26192491明示的な長さとして実際の大きさを指定する必要があります。
26202492
26212493 my $mem = "abcdefghijklmn";
26222494 print unpack( 'P5', pack( 'P', $mem ) ); # prints "abcde"
26232495
26242496=begin original
26252497
26262498As a consequence, C<pack> ignores any number or C<*> after C<P>.
26272499
26282500=end original
26292501
26302502結果として、C<pack> は C<P> の後の数値や C<*> を無視します。
26312503
26322504=begin original
26332505
26342506Now that we have seen C<P> at work, we might as well give C<p> a whirl.
26352507Why do we need a second template code for packing pointers at all? The
26362508answer lies behind the simple fact that an C<unpack> with C<p> promises
26372509a null-terminated string starting at the address taken from the buffer,
26382510and that implies a length for the data item to be returned:
26392511
26402512=end original
26412513
26422514ここで C<P> の動作は見たので、同様に C<p> を試してみます。
26432515とにかく、なぜポインタを pack するのに 2 番目のテンプレートコードが
26442516必要なのでしょう?
26452517答えは、
26462518C<unpack> の C<p> はバッファから取った NUL 終端された文字列がその
26472519アドレスから始まっていることを約束していて、返されるデータアイテムの
26482520長さを暗示しているという単純な事実の後ろに横たわっています:
26492521
26502522 my $buf = pack( 'p', "abc\x00efhijklmn" );
26512523 print unpack( 'p', $buf ); # prints "abc"
26522524
26532525=begin original
26542526
26552527Albeit this is apt to be confusing: As a consequence of the length being
26562528implied by the string's length, a number after pack code C<p> is a repeat
26572529count, not a length as after C<P>.
26582530
26592531=end original
26602532
26612533それでもこれは混乱しがちです: 長さが文字列の長さを暗示しているので、
26622534C<p> の後の数値は繰り返し数であって、C<P> の後のように長さではありません。
26632535
26642536=begin original
26652537
26662538Using C<pack(..., $x)> with C<P> or C<p> to get the address where C<$x> is
26672539actually stored must be used with circumspection. Perl's internal machinery
26682540considers the relation between a variable and that address as its very own
26692541private matter and doesn't really care that we have obtained a copy. Therefore:
26702542
26712543=end original
26722544
26732545C<$x> が実際に保管されているアドレスを得るために C<pack(..., $x)> で
26742546C<P> や C<p> を使うことは慎重に行われなければなりません。
26752547Perl の内部機構は変数とそのアドレスの関係をとてもプライベートな問題と
26762548考え、私たちがコピーを得たことを実際には気にしません。
26772549従って:
26782550
26792551=over 4
26802552
26812553=item *
26822554
26832555=begin original
26842556
26852557Do not use C<pack> with C<p> or C<P> to obtain the address of variable
26862558that's bound to go out of scope (and thereby freeing its memory) before you
26872559are done with using the memory at that address.
26882560
26892561=end original
26902562
26912563その変数のアドレスのメモリを使い終わる前にスコープから出る(従って
26922564メモリが開放される)ような変数のアドレスを得るために
26932565C<pack> の C<p> や C<P> を使わないでください。
26942566
26952567=item *
26962568
26972569=begin original
26982570
26992571Be very careful with Perl operations that change the value of the
27002572variable. Appending something to the variable, for instance, might require
27012573reallocation of its storage, leaving you with a pointer into no-man's land.
27022574
27032575=end original
27042576
27052577変数の値を変更する Perl 操作にとても注意してください。
27062578例えば、値に何かを追加すると、その保管場所を再配置することになって、
27072579ポインタを誰もいないところにしたままにすることに
27082580なるかもしれません。
27092581
27102582=item *
27112583
27122584=begin original
27132585
27142586Don't think that you can get the address of a Perl variable
27152587when it is stored as an integer or double number! C<pack('P', $x)> will
27162588force the variable's internal representation to string, just as if you
27172589had written something like C<$x .= ''>.
27182590
27192591=end original
27202592
27212593整数や倍精度実数として保管されている Perl 変数のアドレスを取れるとは
27222594考えないでください!
27232595C<pack('P', $x)> は、ちょうど C<$x .= ''> のようなものを書いたのと同様に、
27242596変数の内部表現を文字列に強制します。
27252597
27262598=back
27272599
27282600=begin original
27292601
27302602It's safe, however, to P- or p-pack a string literal, because Perl simply
27312603allocates an anonymous variable.
27322604
27332605=end original
27342606
27352607しかし、文字列リテラルを P または p で pack することは安全です;
27362608なぜなら Perl は単に無名変数を割り当てるからです。
27372609
27382610=head1 Pack Recipes
27392611
27402612(pack レシピ)
27412613
27422614=begin original
27432615
27442616Here are a collection of (possibly) useful canned recipes for C<pack>
27452617and C<unpack>:
27462618
27472619=end original
27482620
27492621以下に C<pack> と C<unpack> に関する、(多分)役に立つレシピをまとめます:
27502622
27512623 # Convert IP address for socket functions
27522624 pack( "C4", split /\./, "123.4.5.6" );
27532625
27542626 # Count the bits in a chunk of memory (e.g. a select vector)
27552627 unpack( '%32b*', $mask );
27562628
27572629 # Determine the endianness of your system
27582630 $is_little_endian = unpack( 'c', pack( 's', 1 ) );
27592631 $is_big_endian = unpack( 'xc', pack( 's', 1 ) );
27602632
27612633 # Determine the number of bits in a native integer
27622634 $bits = unpack( '%32I!', ~0 );
27632635
27642636 # Prepare argument for the nanosleep system call
27652637 my $timespec = pack( 'L!L!', $secs, $nanosecs );
27662638
27672639=begin original
27682640
27692641For a simple memory dump we unpack some bytes into just as
27702642many pairs of hex digits, and use C<map> to handle the traditional
27712643spacing - 16 bytes to a line:
27722644
27732645=end original
27742646
27752647単純なメモリダンプのために、バイト列を 16 進数の組に unpack し、
27762648C<map> を使って伝統的な表現 - 1 行に 16 バイト - に加工します:
27772649
27782650 my $i;
27792651 print map( ++$i % 16 ? "$_ " : "$_\n",
27802652 unpack( 'H2' x length( $mem ), $mem ) ),
27812653 length( $mem ) % 16 ? "\n" : '';
27822654
27832655=head1 Funnies Section
27842656
27852657(ネタ部門)
27862658
27872659 # Pulling digits out of nowhere...
27882660 print unpack( 'C', pack( 'x' ) ),
27892661 unpack( '%B*', pack( 'A' ) ),
27902662 unpack( 'H', pack( 'A' ) ),
27912663 unpack( 'A', unpack( 'C', pack( 'A' ) ) ), "\n";
27922664
27932665 # One for the road ;-)
27942666 my $advice = pack( 'all u can in a van' );
27952667
27962668=head1 Authors
27972669
27982670(著者)
27992671
2672=begin original
2673
28002674Simon Cozens and Wolfgang Laun.
28012675
2676=end original
2677
2678Simon Cozens と Wolfgang Laun。
2679
28022680=begin meta
28032681
2804Translate: SHIRAKATA Kentaro <argrath@ub32.org> (5.8.8-)
2682Translate: Kentaro Shirakata <argrath@ub32.org> (5.8.8-)
2805Status: completed
28062683
28072684=end meta