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