perlopentut >
5.40.0
との差分
perlopentut 5.40.0 と 5.10.0 の差分
1 | 1 | |
2 | =encoding u | |
2 | =encoding euc-jp | |
3 | 3 | |
4 | 4 | =head1 NAME |
5 | 5 | |
6 | 6 | =begin original |
7 | 7 | |
8 | perlopentut - | |
8 | perlopentut - tutorial on opening things in Perl | |
9 | 9 | |
10 | 10 | =end original |
11 | 11 | |
12 | perlopentut - Perl で | |
12 | perlopentut - Perl でいろんなものを開くためのチュートリアル | |
13 | 13 | |
14 | 14 | =head1 DESCRIPTION |
15 | 15 | |
16 | 16 | =begin original |
17 | 17 | |
18 | ||
18 | Perl has two simple, built-in ways to open files: the shell way for | |
19 | c | |
19 | convenience, and the C way for precision. The shell way also has 2- and | |
20 | ||
20 | 3-argument forms, which have different semantics for handling the filename. | |
21 | ||
21 | The choice is yours. | |
22 | of the C<close> function to break that association. | |
23 | 22 | |
24 | 23 | =end original |
25 | 24 | |
26 | Perl | |
25 | Perl には、ファイルを開くための 2 つの単純な組み込みの手段があります: | |
27 | ||
26 | 利便性のためのシェル風の方法と、正確性のための C 風の方法です。 | |
28 | ||
27 | シェル風の方法には 2 引数と 3 引数があり、ファイル名の扱いに関して | |
29 | ||
28 | 異なった動作をします。 | |
30 | ||
29 | 選択はあなた次第です。 | |
31 | 30 | |
31 | =head1 Open E<agrave> la shell | |
32 | ||
33 | (シェル風に開く) | |
34 | ||
32 | 35 | =begin original |
33 | 36 | |
34 | ||
37 | Perl's C<open> function was designed to mimic the way command-line | |
35 | ||
38 | redirection in the shell works. Here are some basic examples | |
36 | ||
39 | from the shell: | |
37 | without having to go to the trouble of opening them yourself: | |
38 | 40 | |
39 | 41 | =end original |
40 | 42 | |
41 | ||
43 | Perl の C<open> 関数は、シェルでのコマンドラインのリダイレクトをまねて | |
42 | ||
44 | 設計されています。 | |
43 | ||
45 | 以下はシェルでの基本的な例です: | |
44 | これらは既に開いているので、自分でこれらを開くときの問題を受けることなく | |
45 | 正しく使うことができます。 | |
46 | 46 | |
47 | pr | |
47 | $ myprogram file1 file2 file3 | |
48 | $ myprogram < inputfile | |
49 | $ myprogram > outputfile | |
50 | $ myprogram >> outputfile | |
51 | $ myprogram | otherprogram | |
52 | $ otherprogram | myprogram | |
48 | 53 | |
49 | ||
54 | =begin original | |
50 | $response = <STDIN> // die "how come no input?"; | |
51 | print STDOUT "Thank you!\n"; | |
52 | 55 | |
53 | | |
56 | And here are some more advanced examples: | |
54 | 57 | |
58 | =end original | |
59 | ||
60 | そして以下はもう少し高度な例です: | |
61 | ||
62 | $ otherprogram | myprogram f1 - f2 | |
63 | $ otherprogram 2>&1 | myprogram - | |
64 | $ myprogram <&3 | |
65 | $ myprogram >&4 | |
66 | ||
55 | 67 | =begin original |
56 | 68 | |
57 | ||
69 | Programmers accustomed to constructs like those above can take comfort | |
58 | ||
70 | in learning that Perl directly supports these familiar constructs using | |
59 | i | |
71 | virtually the same syntax as the shell. | |
60 | like the C<@ARGV> array and the C<%ENV> hash are. Their external | |
61 | associations were set up by your shell. | |
62 | 72 | |
63 | 73 | =end original |
64 | 74 | |
65 | ||
75 | 上述のような方法に慣れているプログラマにとっては、Perl がシェルと事実上 | |
66 | ||
76 | 同じ文法を使った親しんでいる構造に直接対応していることは | |
67 | ||
77 | 学ぶのが容易になります。 | |
68 | 予約されているので、全て大文字になっています。 | |
69 | これらの外部関連づけはシェルによって行われます。 | |
70 | 78 | |
79 | =head2 Simple Opens | |
80 | ||
81 | (単純に開く) | |
82 | ||
71 | 83 | =begin original |
72 | 84 | |
73 | ||
85 | The C<open> function takes two arguments: the first is a filehandle, | |
74 | a | |
86 | and the second is a single string comprising both what to open and how | |
75 | ||
87 | to open it. C<open> returns true when it works, and when it fails, | |
88 | returns a false value and sets the special variable C<$!> to reflect | |
89 | the system error. If the filehandle was previously opened, it will | |
90 | be implicitly closed first. | |
76 | 91 | |
77 | 92 | =end original |
78 | 93 | |
79 | ||
94 | C<open> 関数は 2 つの引数を取ります: 1 つめはファイルハンドルで、 | |
80 | ||
95 | 2 つめは何を開くかとどう開くかで構成される単一の文字列です。 | |
81 | ||
96 | C<open> は成功すると真を返し、失敗すると偽を返して特殊変数 C<$!> に | |
97 | システムエラーを反映します。 | |
98 | 指定されたファイルハンドルが以前に開かれていた場合は、暗黙の内に | |
99 | まず閉じられます。 | |
82 | 100 | |
83 | 101 | =begin original |
84 | 102 | |
85 | ||
103 | For example: | |
86 | 104 | |
87 | 105 | =end original |
88 | 106 | |
89 | ||
107 | 例えば: | |
90 | 108 | |
109 | open(INFO, "datafile") || die("can't open datafile: $!"); | |
110 | open(INFO, "< datafile") || die("can't open datafile: $!"); | |
111 | open(RESULTS,"> runstats") || die("can't open runstats: $!"); | |
112 | open(LOG, ">> logfile ") || die("can't open logfile: $!"); | |
113 | ||
91 | 114 | =begin original |
92 | 115 | |
93 | ||
116 | If you prefer the low-punctuation version, you could write that this way: | |
94 | 117 | |
95 | 118 | =end original |
96 | 119 | |
97 | ||
120 | 句読点が少ない方が好みなら、以下のようにも書けます: | |
98 | 121 | |
99 | ||
122 | open INFO, "< datafile" or die "can't open datafile: $!"; | |
123 | open RESULTS,"> runstats" or die "can't open runstats: $!"; | |
124 | open LOG, ">> logfile " or die "can't open logfile: $!"; | |
100 | 125 | |
101 | = | |
126 | =begin original | |
102 | 127 | |
128 | A few things to notice. First, the leading less-than is optional. | |
129 | If omitted, Perl assumes that you want to open the file for reading. | |
130 | ||
131 | =end original | |
132 | ||
133 | いくつか気がつくことがあります。 | |
134 | まず、先頭の「大なり」は省略可能です。 | |
135 | 省略されると、Perl はファイルを読み込みのために開きたいと仮定します。 | |
136 | ||
103 | 137 | =begin original |
104 | 138 | |
105 | ||
139 | Note also that the first example uses the C<||> logical operator, and the | |
106 | ||
140 | second uses C<or>, which has lower precedence. Using C<||> in the latter | |
141 | examples would effectively mean | |
107 | 142 | |
108 | 143 | =end original |
109 | 144 | |
110 | ||
145 | 最初の例は C<||> 論理演算子を使っていて、二つめの例はより優先順位の低い | |
146 | C<or> を使っていることにも注意してください。 | |
147 | 後者の例で C<||> を使うと、実際には以下のような意味になり | |
111 | 148 | |
112 | ||
149 | open INFO, ( "< datafile" || die "can't open datafile: $!" ); | |
113 | 150 | |
114 | 151 | =begin original |
115 | 152 | |
116 | ||
153 | which is definitely not what you want. | |
117 | C<open> function if it succeeds; | |
118 | 154 | |
119 | 155 | =end original |
120 | 156 | |
121 | ||
157 | あなたが望んでいるのと全く違うことになります。 | |
122 | 158 | |
123 | = | |
159 | =begin original | |
124 | 160 | |
161 | The other important thing to notice is that, just as in the shell, | |
162 | any whitespace before or after the filename is ignored. This is good, | |
163 | because you wouldn't want these to do different things: | |
164 | ||
165 | =end original | |
166 | ||
167 | 他の注意するべき重要なこととしては、シェルと同様、ファイル名の前後の | |
168 | 空白は無視されることです。 | |
169 | これはよいことです; なぜなら、以下のものが違うことをすることは | |
170 | 望まないだろうからです: | |
171 | ||
172 | open INFO, "<datafile" | |
173 | open INFO, "< datafile" | |
174 | open INFO, "< datafile" | |
175 | ||
125 | 176 | =begin original |
126 | 177 | |
127 | is | |
178 | Ignoring surrounding whitespace also helps for when you read a filename | |
179 | in from a different file, and forget to trim it before opening: | |
128 | 180 | |
129 | 181 | =end original |
130 | 182 | |
131 | こ | |
183 | 周りの空白を無視することは、ファイル名を別のファイルから読み込んで、 | |
184 | 開く前に空白を取り除くのを忘れたときにも助けになります: | |
132 | 185 | |
133 | ||
186 | $filename = <INFO>; # oops, \n still there | |
187 | open(EXTRA, "< $filename") || die "can't open $filename: $!"; | |
134 | 188 | |
135 | 189 | =begin original |
136 | 190 | |
137 | is | |
191 | This is not a bug, but a feature. Because C<open> mimics the shell in | |
192 | its style of using redirection arrows to specify how to open the file, it | |
193 | also does so with respect to extra whitespace around the filename itself | |
194 | as well. For accessing files with naughty names, see | |
195 | L<"Dispelling the Dweomer">. | |
138 | 196 | |
139 | 197 | =end original |
140 | 198 | |
141 | これは | |
199 | これはバグではありません、仕様です。 | |
200 | C<open> はどのようにファイルを開くかを指定するのにリダイレクトの矢印を | |
201 | 使うことでシェルを真似ているので、ファイル名の周りの空白についても | |
202 | 同じように扱います。 | |
203 | 行儀の悪い名前のファイルにアクセスするためには、 | |
204 | L<"Dispelling the Dweomer"> を参照してください。 | |
142 | 205 | |
143 | =ba | |
206 | =begin original | |
144 | 207 | |
208 | There is also a 3-argument version of C<open>, which lets you put the | |
209 | special redirection characters into their own argument: | |
210 | ||
211 | =end original | |
212 | ||
213 | また、3 引数版の C<open> もあって、これは特殊なリダイレクト文字を | |
214 | 独立した引数にしたものです: | |
215 | ||
216 | open( INFO, ">", $datafile ) || die "Can't create $datafile: $!"; | |
217 | ||
145 | 218 | =begin original |
146 | 219 | |
147 | ||
220 | In this case, the filename to open is the actual string in C<$datafile>, | |
148 | ||
221 | so you don't have to worry about C<$datafile> containing characters | |
222 | that might influence the open mode, or whitespace at the beginning of | |
223 | the filename that would be absorbed in the 2-argument version. Also, | |
224 | any reduction of unnecessary string interpolation is a good thing. | |
149 | 225 | |
150 | 226 | =end original |
151 | 227 | |
152 | C< | |
228 | この場合、開くファイル名は C<$datafile> の実際の文字列なので、 | |
153 | ||
229 | C<$datafile> に開くモードに影響を与える文字や、 | |
230 | 2 引数版では吸収されるファイル名の先頭の空白が含まれているかどうかを | |
231 | 心配する必要はありません。 | |
232 | また、不必要な文字列変換が削減されるのもよいことです。 | |
154 | 233 | |
234 | =head2 Indirect Filehandles | |
235 | ||
236 | (間接ファイルハンドル) | |
237 | ||
155 | 238 | =begin original |
156 | 239 | |
157 | ||
240 | C<open>'s first argument can be a reference to a filehandle. As of | |
158 | ||
241 | perl 5.6.0, if the argument is uninitialized, Perl will automatically | |
159 | ||
242 | create a filehandle and put a reference to it in the first argument, | |
243 | like so: | |
160 | 244 | |
161 | 245 | =end original |
162 | 246 | |
163 | ||
247 | C<open> の最初の引数は、ファイルハンドルへのリファレンスにすることも出来ます。 | |
164 | ||
248 | perl 5.6.0 以降、引数が初期化されていない場合、Perl は | |
165 | ||
249 | 以下のように、自動的にファイルハンドルを作成して、それへのリファレンスを | |
250 | 最初の引数に設定します: | |
166 | 251 | |
167 | ||
252 | open( my $in, $infile ) or die "Couldn't read $infile: $!"; | |
253 | while ( <$in> ) { | |
254 | # do something with $_ | |
255 | } | |
256 | close $in; | |
168 | 257 | |
169 | ||
258 | =begin original | |
170 | 259 | |
171 | ||
260 | Indirect filehandles make namespace management easier. Since filehandles | |
261 | are global to the current package, two subroutines trying to open | |
262 | C<INFILE> will clash. With two functions opening indirect filehandles | |
263 | like C<my $infile>, there's no clash and no need to worry about future | |
264 | conflicts. | |
172 | 265 | |
173 | ||
266 | =end original | |
174 | 267 | |
268 | 間接ファイルハンドルは、名前空間管理をより容易にします。 | |
269 | ファイルハンドルは現在のパッケージに対してグローバルなので、 | |
270 | 二つのサブルーチンが C<INFILE> を開こうとすると衝突します。 | |
271 | 二つの関数が C<my $infil> のように間接ファイルハンドルで開いていると、 | |
272 | 衝突は発生せず、将来の衝突を気にする必要もありません。 | |
273 | ||
175 | 274 | =begin original |
176 | 275 | |
177 | ||
276 | Another convenient behavior is that an indirect filehandle automatically | |
178 | ||
277 | closes when it goes out of scope or when you undefine it: | |
179 | 278 | |
180 | 279 | =end original |
181 | 280 | |
182 | ||
281 | もう一つの便利は振る舞いとして、間接ファイルハンドルは、スコープ外に出るか | |
183 | ||
282 | undef にされると、自動的に閉じます: | |
184 | 283 | |
185 | | |
284 | sub firstline { | |
186 | | |
285 | open( my $in, shift ) && return scalar <$in>; | |
187 | | |
286 | # no close() required | |
287 | } | |
188 | 288 | |
189 | ||
289 | =head2 Pipe Opens | |
190 | || die "$0: can't open $filename for reading: $!"; | |
191 | 290 | |
291 | (パイプを開く) | |
292 | ||
192 | 293 | =begin original |
193 | 294 | |
194 | ||
295 | In C, when you want to open a file using the standard I/O library, | |
195 | ||
296 | you use the C<fopen> function, but when opening a pipe, you use the | |
196 | ||
297 | C<popen> function. But in the shell, you just use a different redirection | |
197 | r | |
298 | character. That's also the case for Perl. The C<open> call | |
299 | remains the same--just its argument differs. | |
198 | 300 | |
199 | 301 | =end original |
200 | 302 | |
201 | ||
303 | C では、標準 I/O ライブラリを使ってファイルを開きたいときは C<fopen> を | |
202 | C< | |
304 | 使いますが、パイプを開くときには C<popen> 関数を使います。 | |
203 | ||
305 | しかし、シェルでは、単に違うリダイレクト文字を使います。 | |
204 | ||
306 | これは Perl の場合にも当てはまります。 | |
307 | C<open> 呼び出しは同じままです -- 単にその引数が変わります。 | |
205 | 308 | |
206 | 309 | =begin original |
207 | 310 | |
208 | ||
311 | If the leading character is a pipe symbol, C<open> starts up a new | |
209 | ||
312 | command and opens a write-only filehandle leading into that command. | |
210 | is | |
313 | This lets you write into that handle and have what you write show up on | |
314 | that command's standard input. For example: | |
211 | 315 | |
212 | 316 | =end original |
213 | 317 | |
214 | ||
318 | 先頭の文字がパイプ記号の場合、C<open> は新しいコマンドを準備して、 | |
215 | ||
319 | そのコマンドへと導かれる書き込み専用のファイルハンドルを開きます。 | |
216 | ||
320 | これによって、あなたがこのハンドルに書き込んだものがコマンドの | |
321 | 標準入力に渡されるようになります。 | |
322 | 例えば: | |
217 | 323 | |
218 | | |
324 | open(PRINTER, "| lpr -Plp1") || die "can't run lpr: $!"; | |
219 | | |
325 | print PRINTER "stuff\n"; | |
326 | close(PRINTER) || die "can't close lpr: $!"; | |
220 | 327 | |
221 | 328 | =begin original |
222 | 329 | |
223 | ||
330 | If the trailing character is a pipe, you start up a new command and open a | |
224 | ||
331 | read-only filehandle leading out of that command. This lets whatever that | |
332 | command writes to its standard output show up on your handle for reading. | |
333 | For example: | |
225 | 334 | |
226 | 335 | =end original |
227 | 336 | |
228 | ||
337 | 末尾の文字がパイプの場合、新しいコマンドを準備して、 | |
229 | ||
338 | そのコマンドから導かれる読み込み専用のファイルハンドルを開きます。 | |
339 | これにより、そのコマンドが標準出力にしたものはなんでも読み込み用の | |
340 | ファイルハンドルに現れます。 | |
341 | 例えば: | |
230 | 342 | |
231 | | |
343 | open(NET, "netstat -i -n |") || die "can't fork netstat: $!"; | |
232 | i | |
344 | while (<NET>) { } # do something with input | |
233 | | |
345 | close(NET) || die "can't close netstat: $!"; | |
234 | } | |
235 | else { | |
236 | # $line is not valid, so skip it | |
237 | } | |
238 | 346 | |
239 | 347 | =begin original |
240 | 348 | |
241 | ||
349 | What happens if you try to open a pipe to or from a non-existent | |
350 | command? If possible, Perl will detect the failure and set C<$!> as | |
351 | usual. But if the command contains special shell characters, such as | |
352 | C<E<gt>> or C<*>, called 'metacharacters', Perl does not execute the | |
353 | command directly. Instead, Perl runs the shell, which then tries to | |
354 | run the command. This means that it's the shell that gets the error | |
355 | indication. In such a case, the C<open> call will only indicate | |
356 | failure if Perl can't even run the shell. See L<perlfaq8/"How can I | |
357 | capture STDERR from an external command?"> to see how to cope with | |
358 | this. There's also an explanation in L<perlipc>. | |
242 | 359 | |
243 | 360 | =end original |
244 | 361 | |
245 | ||
362 | 存在しないコマンドに対してパイプを開こうとすると何が起こるでしょうか? | |
363 | 可能なら、Perl は失敗を検出していつも通り C<$!> をセットします。 | |
364 | しかし、もしコマンドに「メタ文字」と呼ばれる C<E<gt>> や C<*> のような | |
365 | 特殊シェル文字が含まれていると、Perl はコマンドを直接実行しません。 | |
366 | その代わりに、Perl はシェルを実行し、それからコマンドを | |
367 | 実行しようとします。 | |
368 | これは、エラーを受け取るのはシェルであることを意味します。 | |
369 | このような場合、C<open> 呼び出しは、たとえ Perl がシェルを実行できなかった | |
370 | 場合でも、失敗を示すだけです。 | |
371 | これを扱う方法については、 | |
372 | L<perlfaq8/"How can I capture STDERR from an external command?"> を | |
373 | 参照してください。 | |
374 | L<perlipc> にも説明があります。 | |
246 | 375 | |
247 | ||
376 | =begin original | |
248 | 377 | |
378 | If you would like to open a bidirectional pipe, the IPC::Open2 | |
379 | library will handle this for you. Check out | |
380 | L<perlipc/"Bidirectional Communication with Another Process"> | |
381 | ||
382 | =end original | |
383 | ||
384 | 双方向パイプを開きたい場合は、IPC::Open2 ライブラリが使えます。 | |
385 | L<perlipc/"Bidirectional Communication with Another Process"> を | |
386 | 参照してください。 | |
387 | ||
388 | =head2 The Minus File | |
389 | ||
390 | ("-" ファイル) | |
391 | ||
249 | 392 | =begin original |
250 | 393 | |
251 | ||
394 | Again following the lead of the standard shell utilities, Perl's | |
252 | e | |
395 | C<open> function treats a file whose name is a single minus, "-", in a | |
253 | ||
396 | special way. If you open minus for reading, it really means to access | |
254 | the | |
397 | the standard input. If you open minus for writing, it really means to | |
398 | access the standard output. | |
255 | 399 | |
256 | 400 | =end original |
257 | 401 | |
258 | ||
402 | 再び標準シェルの機能に合わせるように、Perl の | |
259 | ||
403 | C<open> 関数は、名前がマイナス一つ "-" だけのファイルを特別に扱います。 | |
260 | ||
404 | 読み込み用にマイナスを開くと、実際には標準入力にアクセスします。 | |
261 | 実際 | |
405 | 書き込み用にマイナスを開くと、実際には標準出力にアクセスします。 | |
262 | 406 | |
263 | ||
407 | =begin original | |
264 | # do something with data in $_ | |
265 | } | |
266 | if ($!) { | |
267 | die "unexpected error while reading from $filename: $!"; | |
268 | } | |
269 | 408 | |
409 | If minus can be used as the default input or default output, what happens | |
410 | if you open a pipe into or out of minus? What's the default command it | |
411 | would run? The same script as you're currently running! This is actually | |
412 | a stealth C<fork> hidden inside an C<open> call. See | |
413 | L<perlipc/"Safe Pipe Opens"> for details. | |
414 | ||
415 | =end original | |
416 | ||
417 | マイナスがデフォルトの入力やデフォルトの出力として使えるとすると、 | |
418 | パイプに対してマイナスを使うとどうなるでしょう? | |
419 | デフォルトのコマンドとして何が実行されるのでしょう? | |
420 | 今実行している同じスクリプトです! | |
421 | これは実際には C<open> 呼び出し内で隠れた C<fork> が行われます。 | |
422 | 詳しくは L<perlipc/"Safe Pipe Opens"> を参照してください。 | |
423 | ||
424 | =head2 Mixing Reads and Writes | |
425 | ||
426 | (読み書きを混ぜる) | |
427 | ||
270 | 428 | =begin original |
271 | 429 | |
272 | ||
430 | It is possible to specify both read and write access. All you do is | |
273 | ||
431 | add a "+" symbol in front of the redirection. But as in the shell, | |
274 | tha | |
432 | using a less-than on a file never creates a new file; it only opens an | |
433 | existing one. On the other hand, using a greater-than always clobbers | |
434 | (truncates to zero length) an existing file, or creates a brand-new one | |
435 | if there isn't an old one. Adding a "+" for read-write doesn't affect | |
436 | whether it only works on existing files or always clobbers existing ones. | |
275 | 437 | |
276 | 438 | =end original |
277 | 439 | |
278 | ||
440 | 読み書きアクセス双方を指定することは可能です。 | |
279 | 必要 | |
441 | 必要なことはリダイレクトの前に "+" の文字を加えるだけです。 | |
280 | ||
442 | しかしシェルの場合と同様、ファイルに小なり記号を使っても新しいファイルが | |
281 | ||
443 | 作成されることはありません; すでにあるファイルを開くだけです。 | |
444 | 一方、大なり記号を使うと、ファイルがある場合には常に上書き | |
445 | (長さ 0 に切り詰め)られ、ファイルがない場合は新しいファイルが作成されます。 | |
446 | 読み書き用に "+" を追加しても、既にあるファイルにだけ動作するか | |
447 | 既にあるファイルを上書きするかということには影響を与えません。 | |
282 | 448 | |
283 | | |
449 | open(WTMP, "+< /usr/adm/wtmp") | |
450 | || die "can't open /usr/adm/wtmp: $!"; | |
284 | 451 | |
452 | open(SCREEN, "+> lkscreen") | |
453 | || die "can't open lkscreen: $!"; | |
454 | ||
455 | open(LOGFILE, "+>> /var/log/applog") | |
456 | || die "can't open /var/log/applog: $!"; | |
457 | ||
285 | 458 | =begin original |
286 | 459 | |
287 | ||
460 | The first one won't create a new file, and the second one will always | |
288 | o | |
461 | clobber an old one. The third one will create a new file if necessary | |
462 | and not clobber an old one, and it will allow you to read at any point | |
463 | in the file, but all writes will always go to the end. In short, | |
464 | the first case is substantially more common than the second and third | |
465 | cases, which are almost always wrong. (If you know C, the plus in | |
466 | Perl's C<open> is historically derived from the one in C's fopen(3S), | |
467 | which it ultimately calls.) | |
289 | 468 | |
290 | 469 | =end original |
291 | 470 | |
292 | 一 | |
471 | 一つ目のものは新しいファイルを作ることはなく、二つ目のものは常に古い | |
472 | ファイルを上書きします。 | |
473 | 三つ目のものは必要があれば新しいファイルを作りますが、古いファイルを | |
474 | 上書きせず、ファイルのどの地点でも読み込むことができますが、 | |
475 | 書き込みは常に末尾に行われます。 | |
476 | 要するに、一つ目のものは(ほとんど常に間違っている)二つ目や三つ目の | |
477 | ものよりもかなり一般的です。 | |
478 | (もし C を知っているなら、Perl の C<open> で使われるプラス記号が | |
479 | 歴史的には (最終的に呼ばれることになる) C の fopen(3S) に由来しています。) | |
293 | 480 | |
294 | ||
481 | =begin original | |
295 | || die "$0: can't open $filename for reading: $!"; | |
296 | 482 | |
483 | In fact, when it comes to updating a file, unless you're working on | |
484 | a binary file as in the WTMP case above, you probably don't want to | |
485 | use this approach for updating. Instead, Perl's B<-i> flag comes to | |
486 | the rescue. The following command takes all the C, C++, or yacc source | |
487 | or header files and changes all their foo's to bar's, leaving | |
488 | the old version in the original filename with a ".orig" tacked | |
489 | on the end: | |
490 | ||
491 | =end original | |
492 | ||
493 | 実際、ファイルを更新するとき、上述の WTMP の場合のようなバイナリファイルに | |
494 | 対して作業をするのでない限り、おそらく更新のためにこの手法を | |
495 | 使いたくないでしょう。 | |
496 | 代わりに、Perl の B<-i> フラグが助けになります。 | |
497 | 以下のコマンドは C, C++, yacc 全てののソースファイルとヘッダファイルを | |
498 | 取って、その中の全ての foo を bar に変更し、原版は元のファイル名の末尾に | |
499 | ".orig" を付けたファイルに保持します: | |
500 | ||
501 | $ perl -i.orig -pe 's/\bfoo\b/bar/g' *.[Cchy] | |
502 | ||
297 | 503 | =begin original |
298 | 504 | |
299 | ||
505 | This is a short cut for some renaming games that are really | |
300 | ||
506 | the best way to update textfiles. See the second question in | |
301 | ||
507 | L<perlfaq5> for more details. | |
302 | map the data in your file into actual characters it can work with. Other | |
303 | common encoding formats including C<"ASCII">, C<"ISO-8859-1">, | |
304 | C<"ISO-8859-15">, C<"Windows-1252">, C<"MacRoman">, and even C<"UTF-16LE">. | |
305 | See L<perlunitut> for more about encodings. | |
306 | 508 | |
307 | 509 | =end original |
308 | 510 | |
309 | ||
511 | これは実際にはテキストファイルを更新するための最良の方法であるリネーム | |
310 | ||
512 | 手法へのショートカットです。 | |
311 | さ | |
513 | さらなる詳細については L<perlfaq5> の 2 番目の質問を参照してください。 | |
312 | 種類のうちどれかを知ることができず、Perl はあなたのファイルのデータを | |
313 | 動作させるための実際の文字にマッピングすることができません。 | |
314 | その他のよくあるエンコーディング形式には | |
315 | C<"ASCII">, C<"ISO-8859-1">, | |
316 | C<"ISO-8859-15">, C<"Windows-1252">, C<"MacRoman"> および、 | |
317 | C<"UTF-16LE"> すらもあります。 | |
318 | エンコーディングに関するさらなる情報については L<perlunitut> を | |
319 | 参照してください。 | |
320 | 514 | |
321 | =head2 | |
515 | =head2 Filters | |
322 | 516 | |
323 | ( | |
517 | (フィルタ) | |
324 | 518 | |
325 | 519 | =begin original |
326 | 520 | |
327 | ||
521 | One of the most common uses for C<open> is one you never | |
328 | ||
522 | even notice. When you process the ARGV filehandle using | |
329 | ||
523 | C<< <ARGV> >>, Perl actually does an implicit open | |
524 | on each file in @ARGV. Thus a program called like this: | |
330 | 525 | |
331 | 526 | =end original |
332 | 527 | |
333 | ||
528 | C<open> のもっとも一般的な使い方の一つは、使っていることを | |
334 | ||
529 | 気づきすらしないものです。 | |
335 | ||
530 | ARGV ファイルハンドルを C<< <ARGV> >> を使って処理するとき、Perl は | |
531 | 実際は @ARGV の各ファイルを暗黙の内に開いています。 | |
532 | 従って、以下のようなプログラムは: | |
336 | 533 | |
534 | $ myprogram file1 file2 file3 | |
535 | ||
337 | 536 | =begin original |
338 | 537 | |
339 | ||
538 | can have all its files opened and processed one at a time | |
340 | in a | |
539 | using a construct no more complex than: | |
341 | existing file in append mode. C<<< ">>" >>> creates the file if it does not | |
342 | already exist. | |
343 | 540 | |
344 | 541 | =end original |
345 | 542 | |
346 | ||
543 | 以下のようなものより複雑な構文を使わなくても、それぞれのファイルを | |
347 | ||
544 | 開いて一度に処理できます: | |
348 | C<<< ">>" >>> が使われます。 | |
349 | ファイルがない場合、C<<< ">>" >>> はファイルを作ります。 | |
350 | 545 | |
351 | | |
546 | while (<>) { | |
352 | | |
547 | # do something with $_ | |
353 | | |
548 | } | |
354 | 549 | |
355 | ||
550 | =begin original | |
356 | || die "$0: can't open $filename for appending: $!"; | |
357 | 551 | |
552 | If @ARGV is empty when the loop first begins, Perl pretends you've opened | |
553 | up minus, that is, the standard input. In fact, $ARGV, the currently | |
554 | open file during C<< <ARGV> >> processing, is even set to "-" | |
555 | in these circumstances. | |
556 | ||
557 | =end original | |
558 | ||
559 | ループが最初に開始したときに @ARGV が空なら、Perl はマイナス記号 | |
560 | (つまり標準入力) を開いたかのように振る舞います。 | |
561 | 実際、C<< <ARGV> >> で現在開いているファイルを示す $ARGV には、 | |
562 | この慣習によって "-" がセットされます。 | |
563 | ||
358 | 564 | =begin original |
359 | 565 | |
360 | ||
566 | You are welcome to pre-process your @ARGV before starting the loop to | |
361 | ||
567 | make sure it's to your liking. One reason to do this might be to remove | |
568 | command options beginning with a minus. While you can always roll the | |
569 | simple ones by hand, the Getopts modules are good for this: | |
362 | 570 | |
363 | 571 | =end original |
364 | 572 | |
365 | ||
573 | 好みの形にするために、ループの開始前に @ARGV を前処理しても問題ありません。 | |
366 | ||
574 | こうするための理由の一つは、マイナスから始まるコマンドオプションを | |
575 | 削除するためです。 | |
576 | いつでも自分で単純なものを作ることができる一方、 | |
577 | Getopts モジュールはこれを行うのによいものです: | |
367 | 578 | |
579 | use Getopt::Std; | |
580 | ||
581 | # -v, -D, -o ARG, sets $opt_v, $opt_D, $opt_o | |
582 | getopts("vDo:"); | |
583 | ||
584 | # -v, -D, -o ARG, sets $args{v}, $args{D}, $args{o} | |
585 | getopts("vDo:", \%args); | |
586 | ||
368 | 587 | =begin original |
369 | 588 | |
370 | ||
589 | Or the standard Getopt::Long module to permit named arguments: | |
371 | will create it for you. But if the file does already exist, its contents are | |
372 | safe from harm because you will be adding your new text past the end of the | |
373 | old text. | |
374 | 590 | |
375 | 591 | =end original |
376 | 592 | |
377 | 前 | |
593 | あるいは、名前付きの引数を使えるようにするための | |
378 | ||
594 | 標準の Getopt::Long モジュールもあります: | |
379 | しかしファイルが既に存在している場合、その内容は保護されます; 新しいテキストは | |
380 | 既存のテキストの末尾に追加されるからです。 | |
381 | 595 | |
596 | use Getopt::Long; | |
597 | GetOptions( "verbose" => \$verbose, # --verbose | |
598 | "Debug" => \$debug, # --Debug | |
599 | "output=s" => \$output ); | |
600 | # --output=somestring or --output somestring | |
601 | ||
382 | 602 | =begin original |
383 | 603 | |
384 | ||
604 | Another reason for preprocessing arguments is to make an empty | |
385 | ||
605 | argument list default to all files: | |
386 | in write-only mode: | |
387 | 606 | |
388 | 607 | =end original |
389 | 608 | |
390 | 一 | |
609 | 引数を前処理するためのもう一つの理由は、空引数リストの時は | |
391 | ||
610 | デフォルトで全てのファイルとする場合です: | |
392 | 開くことができます: | |
393 | 611 | |
394 | | |
612 | @ARGV = glob("*") unless @ARGV; | |
395 | my $filename = "/some/path/to/a/textfile/goes/here"; | |
396 | my $encoding = ":encoding(UTF-8)"; | |
397 | 613 | |
398 | ||
614 | =begin original | |
399 | || die "$0: can't open $filename in write-open mode: $!"; | |
400 | 615 | |
616 | You could even filter out all but plain, text files. This is a bit | |
617 | silent, of course, and you might prefer to mention them on the way. | |
618 | ||
619 | =end original | |
620 | ||
621 | プレーンなテキストファイル以外をフィルタリングすることもできます。 | |
622 | これはもちろん少し静かなので、途中でそれに言及したいかもしれません。 | |
623 | ||
624 | @ARGV = grep { -f && -T } @ARGV; | |
625 | ||
401 | 626 | =begin original |
402 | 627 | |
403 | ||
628 | If you're using the B<-n> or B<-p> command-line options, you | |
404 | an | |
629 | should put changes to @ARGV in a C<BEGIN{}> block. | |
405 | 630 | |
406 | 631 | =end original |
407 | 632 | |
408 | ||
633 | もし B<-n> や B<-p> のコマンドラインオプションを使っているなら、 | |
409 | ||
634 | @ARGV への変更は C<BEGIN{}> ブロックで行うべきです。 | |
410 | 635 | |
411 | 636 | =begin original |
412 | 637 | |
413 | ||
638 | Remember that a normal C<open> has special properties, in that it might | |
414 | ||
639 | call fopen(3S) or it might called popen(3S), depending on what its | |
415 | ||
640 | argument looks like; that's why it's sometimes called "magic open". | |
641 | Here's an example: | |
416 | 642 | |
417 | 643 | =end original |
418 | 644 | |
419 | ||
645 | 通常の C<open> は特別な特性を持っていて、引数が何に見えるかによって、 | |
420 | ||
646 | fopen(3S) を呼ぶかもしれませんし、popen(3S) を呼ぶかもしれません; | |
421 | ||
647 | これが時々「マジカルに開く」と呼ばれる理由です。 | |
648 | 以下は例です: | |
422 | 649 | |
650 | $pwdinfo = `domainname` =~ /^(\(none\))?$/ | |
651 | ? '< /etc/passwd' | |
652 | : 'ypcat passwd |'; | |
653 | ||
654 | open(PWD, $pwdinfo) | |
655 | or die "can't open $pwdinfo: $!"; | |
656 | ||
423 | 657 | =begin original |
424 | 658 | |
425 | ||
659 | This sort of thing also comes into play in filter processing. Because | |
426 | ||
660 | C<< <ARGV> >> processing employs the normal, shell-style Perl C<open>, | |
427 | ||
661 | it respects all the special things we've already seen: | |
428 | 662 | |
429 | 663 | =end original |
430 | 664 | |
431 | ||
665 | このようなことはフィルタ処理でも起こります。 | |
432 | ||
666 | C<< <ARGV> >> 処理は通常のシェル風の Perl C<open> を用いるので、 | |
433 | ||
667 | 今までに見てきた全ての特別なことが反映されます: | |
434 | おそらくあなたが望んでいることをしないからです。 | |
435 | 詳しくは L<perlfaq5> を参照してください。 | |
436 | 668 | |
437 | ||
669 | $ myprogram f1 "cmd1|" - f2 "cmd2|" f3 < tmpfile | |
438 | 670 | |
439 | ||
671 | =begin original | |
440 | 672 | |
673 | That program will read from the file F<f1>, the process F<cmd1>, standard | |
674 | input (F<tmpfile> in this case), the F<f2> file, the F<cmd2> command, | |
675 | and finally the F<f3> file. | |
676 | ||
677 | =end original | |
678 | ||
679 | このプログラムはファイル F<f1>、プロセス F<cmd1>、標準入力 | |
680 | (この場合は F<tmpfile>)、ファイル F<f2>、コマンド F<cmd2>、 | |
681 | ファイル F<f3> から読み込みます。 | |
682 | ||
441 | 683 | =begin original |
442 | 684 | |
443 | ||
685 | Yes, this also means that if you have files named "-" (and so on) in | |
444 | ||
686 | your directory, they won't be processed as literal files by C<open>. | |
445 | ||
687 | You'll need to pass them as "./-", much as you would for the I<rm> program, | |
688 | or you could use C<sysopen> as described below. | |
446 | 689 | |
447 | 690 | =end original |
448 | 691 | |
449 | ||
692 | はい、これは、"-" (あるいは同じような) 名前を持つファイルがある場合、 | |
450 | ||
693 | C<open> によってそのまま処理することができないことも意味します。 | |
451 | ||
694 | I<rm> プログラムに対して行うのと同様に "./-" という形で渡すか、後述する | |
452 | ||
695 | C<sysopen> を使う必要があります。 | |
453 | 696 | |
454 | ||
697 | =begin original | |
455 | my $encoding = ":raw :bytes" | |
456 | my $handle = undef; # this will be filled in on success | |
457 | 698 | |
699 | One of the more interesting applications is to change files of a certain | |
700 | name into pipes. For example, to autoprocess gzipped or compressed | |
701 | files by decompressing them with I<gzip>: | |
702 | ||
703 | =end original | |
704 | ||
705 | もっと興味深いアプリケーションの一つは、ある名前を持ったファイルを | |
706 | パイプに変更するものです。 | |
707 | 例えば、gzip や compress されたファイルを、I<gzip> を使って自動的に | |
708 | 展開するには: | |
709 | ||
710 | @ARGV = map { /^\.(gz|Z)$/ ? "gzip -dc $_ |" : $_ } @ARGV; | |
711 | ||
458 | 712 | =begin original |
459 | 713 | |
460 | ||
714 | Or, if you have the I<GET> program installed from LWP, | |
461 | ||
715 | you can fetch URLs before processing them: | |
462 | 716 | |
463 | 717 | =end original |
464 | 718 | |
465 | ||
719 | あるいは、LWP からインストールされる I<GET> プログラムがあるなら、 | |
466 | ||
720 | 処理する前に URL をフェッチできます: | |
467 | 721 | |
468 | | |
722 | @ARGV = map { m#^\w+://# ? "GET $_ |" : $_ } @ARGV; | |
469 | || die "$0: can't open $filename for reading: $!"; | |
470 | 723 | |
471 | ||
724 | =begin original | |
472 | || die "$0: can't open $filename for appending: $!"; | |
473 | 725 | |
474 | | |
726 | It's not for nothing that this is called magic C<< <ARGV> >>. | |
475 | ||
727 | Pretty nifty, eh? | |
476 | 728 | |
729 | =end original | |
730 | ||
731 | これがマジカルな C<< <ARGV> >> と呼ばれるのは理由のないことではありません。 | |
732 | かなりしゃれてるでしょ? | |
733 | ||
734 | =head1 Open E<agrave> la C | |
735 | ||
736 | (C 風に開く) | |
737 | ||
477 | 738 | =begin original |
478 | 739 | |
479 | ||
740 | If you want the convenience of the shell, then Perl's C<open> is | |
741 | definitely the way to go. On the other hand, if you want finer precision | |
742 | than C's simplistic fopen(3S) provides you should look to Perl's | |
743 | C<sysopen>, which is a direct hook into the open(2) system call. | |
744 | That does mean it's a bit more involved, but that's the price of | |
745 | precision. | |
480 | 746 | |
481 | 747 | =end original |
482 | 748 | |
483 | ||
749 | シェルの便利さを求めているなら、Perl の C<open> はまさにぴったりです。 | |
484 | ||
750 | 一方、C の単純な fopen(3S) が提供しているものより高い精度を求めているなら、 | |
751 | open(2) システムコールへの直接的なフックである、Perl の | |
752 | C<sysopen> を見るべきです。 | |
753 | これはもう少し深く関わることを意味しますが、これは精度のコストです。 | |
485 | 754 | |
486 | ||
755 | =begin original | |
487 | 756 | |
757 | C<sysopen> takes 3 (or 4) arguments. | |
758 | ||
759 | =end original | |
760 | ||
761 | C<sysopen> は 3 (または 4) 引数を取ります。 | |
762 | ||
763 | sysopen HANDLE, PATH, FLAGS, [MASK] | |
764 | ||
488 | 765 | =begin original |
489 | 766 | |
490 | Th | |
767 | The HANDLE argument is a filehandle just as with C<open>. The PATH is | |
768 | a literal path, one that doesn't pay attention to any greater-thans or | |
769 | less-thans or pipes or minuses, nor ignore whitespace. If it's there, | |
770 | it's part of the path. The FLAGS argument contains one or more values | |
771 | derived from the Fcntl module that have been or'd together using the | |
772 | bitwise "|" operator. The final argument, the MASK, is optional; if | |
773 | present, it is combined with the user's current umask for the creation | |
774 | mode of the file. You should usually omit this. | |
491 | 775 | |
492 | 776 | =end original |
493 | 777 | |
494 | ||
778 | HANDLE 引数は C<open> と同様のファイルハンドルです。 | |
779 | PATH はリテラルなパスで、大なりや小なりやパイプやマイナスや空白の | |
780 | 無視といったことに一切注意を払いません。 | |
781 | もしこれらの文字があれば、それはパスの一部です。 | |
782 | FLAGS 引数は、ビット単位 "|" 演算子で結合できる、Fcntl モジュールに | |
783 | 由来する一つ以上の値を指定します。 | |
784 | 最後の引数である MASK はオプションです; もしあれば、これは | |
785 | ファイルの作成モードのためのユーザーの現在の umask と組み合わされます。 | |
786 | 普通はこれは省略するべきです。 | |
495 | 787 | |
496 | ||
788 | =begin original | |
497 | binmode(STDOUT) || die "cannot binmode STDOUT"; | |
498 | 789 | |
790 | Although the traditional values of read-only, write-only, and read-write | |
791 | are 0, 1, and 2 respectively, this is known not to hold true on some | |
792 | systems. Instead, it's best to load in the appropriate constants first | |
793 | from the Fcntl module, which supplies the following standard flags: | |
794 | ||
795 | =end original | |
796 | ||
797 | 読み込み専用、書き込み専用、読み書きを示す伝統的な値は | |
798 | それぞれ 0, 1, 2 ですが、これが正しくないシステムもあることが | |
799 | 知られています。 | |
800 | 代わりに、以下の標準フラグを提供している Fcntl モジュールから | |
801 | 最初に適切な定数を読み込むのが最善です: | |
802 | ||
803 | O_RDONLY Read only | |
804 | O_WRONLY Write only | |
805 | O_RDWR Read and write | |
806 | O_CREAT Create the file if it doesn't exist | |
807 | O_EXCL Fail if the file already exists | |
808 | O_APPEND Append to the file | |
809 | O_TRUNC Truncate the file | |
810 | O_NONBLOCK Non-blocking access | |
811 | ||
499 | 812 | =begin original |
500 | 813 | |
501 | ||
814 | Less common flags that are sometimes available on some operating | |
502 | ||
815 | systems include C<O_BINARY>, C<O_TEXT>, C<O_SHLOCK>, C<O_EXLOCK>, | |
816 | C<O_DEFER>, C<O_SYNC>, C<O_ASYNC>, C<O_DSYNC>, C<O_RSYNC>, | |
817 | C<O_NOCTTY>, C<O_NDELAY> and C<O_LARGEFILE>. Consult your open(2) | |
818 | manpage or its local equivalent for details. (Note: starting from | |
819 | Perl release 5.6 the C<O_LARGEFILE> flag, if available, is automatically | |
820 | added to the sysopen() flags because large files are the default.) | |
503 | 821 | |
504 | 822 | =end original |
505 | 823 | |
506 | ||
824 | オペレーティングシステムによっては、 | |
507 | ||
825 | C<O_BINARY>, C<O_TEXT>, C<O_SHLOCK>, C<O_EXLOCK>, | |
508 | ||
826 | C<O_DEFER>, C<O_SYNC>, C<O_ASYNC>, C<O_DSYNC>, C<O_RSYNC>, | |
509 | ||
827 | C<O_NOCTTY>, C<O_NDELAY>, C<O_LARGEFILE> のような、それほど有名ではない | |
828 | フラグも利用可能です。 | |
829 | 詳しくは open(2) man ページその等価物を参照してください。 | |
830 | (注意: Perl リリース 5.6 から、もし利用可能なら、sysopen() のフラグに | |
831 | 自動的に C<O_LARGEFILE> フラグが付きます; 大きなファイルがデフォルトに | |
832 | なったからです。) | |
510 | 833 | |
511 | ||
834 | =begin original | |
512 | binmode(STDOUT, ":encoding(UTF-8)") || die "cannot binmode STDOUT"; | |
513 | 835 | |
836 | Here's how to use C<sysopen> to emulate the simple C<open> calls we had | |
837 | before. We'll omit the C<|| die $!> checks for clarity, but make sure | |
838 | you always check the return values in real code. These aren't quite | |
839 | the same, since C<open> will trim leading and trailing whitespace, | |
840 | but you'll get the idea. | |
841 | ||
842 | =end original | |
843 | ||
844 | これは、前述した単純な C<open> をエミュレートするために C<sysopen> を | |
845 | 使う方法です。 | |
846 | 明確化のために C<|| die $!> のチェックは省略しましたが、実際のコードでは | |
847 | 常に返り値をチェックするようにしてください。 | |
848 | C<open> は前後の空白を削除するのでこれは全く同じというわけではありませんが、 | |
849 | 想像はできるでしょう。 | |
850 | ||
514 | 851 | =begin original |
515 | 852 | |
516 | ||
853 | To open a file for reading: | |
517 | use all the same Perl I/O functions as you used on text files. However, | |
518 | you may wish to use the fixed-size C<read> instead of the variable-sized | |
519 | C<readline> for your input. | |
520 | 854 | |
521 | 855 | =end original |
522 | 856 | |
523 | ||
857 | ファイルを読み込み用に開くには: | |
524 | 使ったものと全て同じ Perl I/O 関数を使えます。 | |
525 | しかし、入力に対して可変長の C<readline> ではなく固定長の | |
526 | C<read> を使った方が良いでしょう。 | |
527 | 858 | |
859 | open(FH, "< $path"); | |
860 | sysopen(FH, $path, O_RDONLY); | |
861 | ||
528 | 862 | =begin original |
529 | 863 | |
530 | ||
864 | To open a file for writing, creating a new file if needed or else truncating | |
865 | an old file: | |
531 | 866 | |
532 | 867 | =end original |
533 | 868 | |
534 | ||
869 | ファイルを書き込み用に開いて、必要なら新しいファイルを作り、そうでなければ | |
870 | 古いファイルを切り詰めるには: | |
535 | 871 | |
536 | | |
872 | open(FH, "> $path"); | |
537 | | |
873 | sysopen(FH, $path, O_WRONLY | O_TRUNC | O_CREAT); | |
538 | my $name_out = "/some/output/flie"; | |
539 | 874 | |
540 | ||
875 | =begin original | |
541 | 876 | |
542 | open | |
877 | To open a file for appending, creating one if necessary: | |
543 | || die "$0: cannot open $name_in for reading: $!"; | |
544 | open($out_fh, ">", $name_out) | |
545 | || die "$0: cannot open $name_out for writing: $!"; | |
546 | 878 | |
547 | | |
879 | =end original | |
548 | binmode($fh) || die "binmode failed"; | |
549 | } | |
550 | 880 | |
551 | ||
881 | ファイルを追加用に開いて、もし必要なら新しいファイルを作るには: | |
552 | unless (print $out_fh $buffer) { | |
553 | die "couldn't write to $name_out: $!"; | |
554 | } | |
555 | } | |
556 | 882 | |
557 | | |
883 | open(FH, ">> $path"); | |
558 | | |
884 | sysopen(FH, $path, O_WRONLY | O_APPEND | O_CREAT); | |
559 | 885 | |
560 | = | |
886 | =begin original | |
561 | 887 | |
562 | ||
888 | To open a file for update, where the file must already exist: | |
563 | 889 | |
890 | =end original | |
891 | ||
892 | 既に存在しているファイルを更新用に開くには: | |
893 | ||
894 | open(FH, "+< $path"); | |
895 | sysopen(FH, $path, O_RDWR); | |
896 | ||
564 | 897 | =begin original |
565 | 898 | |
566 | ||
899 | And here are things you can do with C<sysopen> that you cannot do with | |
567 | ||
900 | a regular C<open>. As you'll see, it's just a matter of controlling the | |
568 | f | |
901 | flags in the third argument. | |
569 | to receive data from another program for your own Perl program to | |
570 | process. | |
571 | 902 | |
572 | 903 | =end original |
573 | 904 | |
574 | ||
905 | そしてここでは普通の C<open> では出来ないことを C<sysopen> でしています。 | |
575 | ||
906 | 見てきたように、これは単に 3 番目の引数のフラグの制御の問題です。 | |
576 | これを、更なる処理のために Perl プログラムから外部コマンドへ渡すため、 | |
577 | または処理する Perl プログラムのために他のプログラムからデータを | |
578 | 受け取るために行えます。 | |
579 | 907 | |
580 | 908 | =begin original |
581 | 909 | |
582 | ||
910 | To open a file for writing, creating a new file which must not previously | |
583 | ||
911 | exist: | |
584 | filehandle has an active program instead of a static file on its | |
585 | external end, but in every other sense it works just like a more typical | |
586 | file-based filehandle, with all the techniques discussed earlier in this | |
587 | article just as applicable. | |
588 | 912 | |
589 | 913 | =end original |
590 | 914 | |
591 | ||
915 | 既に存在していたりはしない新しいファイルを作成して、ファイルを書き込み用に | |
592 | ||
916 | 開くには: | |
593 | 動作するからです。 | |
594 | そのようなファイルハンドルは、外側が静的なファイルではなく | |
595 | 動作中のプログラムですが、それ以外の点については | |
596 | より典型的なファイルベースのファイルハンドルとちょうど同じように | |
597 | 動作し、この文書で既に議論した全てのテクニックが利用可能です。 | |
598 | 917 | |
918 | sysopen(FH, $path, O_WRONLY | O_EXCL | O_CREAT); | |
919 | ||
599 | 920 | =begin original |
600 | 921 | |
601 | ||
922 | To open a file for appending, where that file must already exist: | |
602 | opening files, setting the second (C<MODE>) argument to special | |
603 | characters that indicate either an input or an output pipe. Use C<"-|"> for a | |
604 | filehandle that will let your Perl program read data from an external | |
605 | program, and C<"|-"> for a filehandle that will send data to that | |
606 | program instead. | |
607 | 923 | |
608 | 924 | =end original |
609 | 925 | |
610 | ||
926 | 既に存在している必要があるファイルを追加用に開くには: | |
611 | 設定することで、ファイルを開くのに使うのと同じ C<open> で | |
612 | パイプを開きます。 | |
613 | Perl プログラムが外部プログラムからデータを読み込むファイルハンドルには | |
614 | C<"-|"> を使います; プログラムにデータを送るファイルハンドルには | |
615 | C<"|-"> を使います。 | |
616 | 927 | |
617 | ||
928 | sysopen(FH, $path, O_WRONLY | O_APPEND); | |
618 | 929 | |
619 | ||
930 | =begin original | |
620 | 931 | |
932 | To open a file for update, creating a new file if necessary: | |
933 | ||
934 | =end original | |
935 | ||
936 | 必要なら新しいファイルを作成して、ファイルを更新用に開くには: | |
937 | ||
938 | sysopen(FH, $path, O_RDWR | O_CREAT); | |
939 | ||
621 | 940 | =begin original |
622 | 941 | |
623 | ||
942 | To open a file for update, where that file must not already exist: | |
624 | directory called C<unsorted>, which contains a number of textfiles. | |
625 | You'd also like your program to sort all the contents from these files | |
626 | into a single, alphabetically sorted list of unique lines before it | |
627 | starts processing them. | |
628 | 943 | |
629 | 944 | =end original |
630 | 945 | |
631 | たくさんのテキストファイルが含まれている、C<unsorted> と呼ばれる | |
632 | 近くのディレクトリに保管されているデータを処理する | |
633 | Perl プログラムが欲しいとしましょう。 | |
634 | また、処理を開始する前に、複数のファイルを単一の、ユニークな行を | |
635 | アルファベット順にソートしたいとします。 | |
636 | 946 | |
947 | 予め存在していてはならないファイルを交信用に開くには: | |
948 | ||
949 | sysopen(FH, $path, O_RDWR | O_EXCL | O_CREAT); | |
950 | ||
637 | 951 | =begin original |
638 | 952 | |
639 | ||
953 | To open a file without blocking, creating one if necessary: | |
640 | those files, gradually building up an in-memory array of all the file | |
641 | contents you load this way, and finally sorting and filtering that array | |
642 | when you've run out of files to load. I<Or>, you could offload all that | |
643 | merging and sorting into your operating system's own C<sort> command by | |
644 | opening a pipe directly into its output, and get to work that much | |
645 | faster. | |
646 | 954 | |
647 | 955 | =end original |
648 | 956 | |
649 | ||
957 | 必要ならファイルを作成して、ファイルをブロックせずに開くには: | |
650 | このようにして読み込んだ全てのファイルの内容を徐々にメモリ内の配列に | |
651 | 構築し、読み込むファイルがなくなったら最後にソートとフィルタリングをする、 | |
652 | という形でこれを行うことも出来ます。 | |
653 | I<あるいは>、結合とソートをオペレーティング自身の C<sort> コマンドに | |
654 | 任せて、その出力を直接パイプで開くことで、遙かに速く作業することも出来ます。 | |
655 | 958 | |
959 | sysopen(FH, $path, O_WRONLY | O_NONBLOCK | O_CREAT); | |
960 | ||
961 | =head2 Permissions E<agrave> la mode | |
962 | ||
963 | (権限モード) | |
964 | ||
656 | 965 | =begin original |
657 | 966 | |
658 | ||
967 | If you omit the MASK argument to C<sysopen>, Perl uses the octal value | |
968 | 0666. The normal MASK to use for executables and directories should | |
969 | be 0777, and for anything else, 0666. | |
659 | 970 | |
660 | 971 | =end original |
661 | 972 | |
662 | ||
973 | C<sysopen> の MASK 引数を省略すると、Perl は 8 進数の 0666 を使います。 | |
974 | 実行ファイルとディレクトリに対する通常の MASK は 0777で、それ以外の | |
975 | ファイルでは 0666 です。 | |
663 | 976 | |
664 | ||
977 | =begin original | |
665 | or die "Couldn't open a pipe into sort: $!"; | |
666 | 978 | |
667 | | |
979 | Why so permissive? Well, it isn't really. The MASK will be modified | |
668 | | |
980 | by your process's current C<umask>. A umask is a number representing | |
669 | | |
981 | I<disabled> permissions bits; that is, bits that will not be turned on | |
670 | ||
982 | in the created files' permissions field. | |
671 | # | |
672 | } | |
673 | 983 | |
984 | =end original | |
985 | ||
986 | なぜそんなに権限を与えるのでしょう? | |
987 | えっと、実際にはそうではありません。 | |
988 | MASK はプロセスの現在の C<umask> で修正されます。 | |
989 | umask は I<無効にする> 許可ビットを表現する数値です; つまり、 | |
990 | 作成したファイルの許可フィールドを有効にすることはないということです。 | |
991 | ||
674 | 992 | =begin original |
675 | 993 | |
676 | ||
994 | For example, if your C<umask> were 027, then the 020 part would | |
677 | s | |
995 | disable the group from writing, and the 007 part would disable others | |
996 | from reading, writing, or executing. Under these conditions, passing | |
997 | C<sysopen> 0666 would create a file with mode 0640, since C<0666 & ~027> | |
998 | is 0640. | |
678 | 999 | |
679 | 1000 | =end original |
680 | 1001 | |
681 | C< | |
1002 | 例えば、C<umask> が 027 の場合、020 の部分はグループによる書き込みと | |
682 | ||
1003 | 実行を無効にし、007 の部分は他のユーザーによる読み込み、書き込み、 | |
1004 | 実行を無効にします。 | |
1005 | この条件では、C<sysopen> に 0666 を渡すとモード 0640 でファイルを作ります; | |
1006 | C<0666 & ~027> は 0640 だからです。 | |
683 | 1007 | |
684 | 1008 | =begin original |
685 | 1009 | |
686 | ||
1010 | You should seldom use the MASK argument to C<sysopen()>. That takes | |
687 | ||
1011 | away the user's freedom to choose what permission new files will have. | |
688 | ||
1012 | Denying choice is almost always a bad thing. One exception would be for | |
689 | ||
1013 | cases where sensitive or private data is being stored, such as with mail | |
690 | ||
1014 | folders, cookie files, and internal temporary files. | |
691 | from it as if it were opened onto an ordinary, single file. | |
692 | 1015 | |
693 | 1016 | =end original |
694 | 1017 | |
695 | C<open> | |
1018 | C<sysopen()> に MASK 引数を使うことはほとんどないでしょう。 | |
696 | ||
1019 | これは、新しいファイルにどのパーミッションを与えるかというユーザーの | |
697 | ||
1020 | 自由を奪います。 | |
698 | ||
1021 | 選択を拒むということは、ほとんど常に悪いことです。 | |
699 | ||
1022 | 一つの例外は、メールフォルダ、クッキーファイル、内部用一時ファイルのような、 | |
700 | ||
1023 | 微妙な、あるいはプライベートなデータを保管する場合でしょう。 | |
701 | プログラムは、通常の単一のファイルが開かれたかのように、 | |
702 | 引き続いてそこからデータを読み込むことができます。 | |
703 | 1024 | |
704 | =head | |
1025 | =head1 Obscure Open Tricks | |
705 | 1026 | |
706 | ( | |
1027 | (わかりにくい開くときの小技) | |
707 | 1028 | |
1029 | =head2 Re-Opening Files (dups) | |
1030 | ||
1031 | (ファイルを再び開く(dup)) | |
1032 | ||
708 | 1033 | =begin original |
709 | 1034 | |
710 | ||
1035 | Sometimes you already have a filehandle open, and want to make another | |
711 | ||
1036 | handle that's a duplicate of the first one. In the shell, we place an | |
712 | ||
1037 | ampersand in front of a file descriptor number when doing redirections. | |
713 | ||
1038 | For example, C<< 2>&1 >> makes descriptor 2 (that's STDERR in Perl) | |
1039 | be redirected into descriptor 1 (which is usually Perl's STDOUT). | |
1040 | The same is essentially true in Perl: a filename that begins with an | |
1041 | ampersand is treated instead as a file descriptor if a number, or as a | |
1042 | filehandle if a string. | |
714 | 1043 | |
715 | 1044 | =end original |
716 | 1045 | |
717 | ||
1046 | 既に開いているファイルハンドルを持っている時に、これを複製して | |
718 | ||
1047 | もう一つのハンドルがほしくなる場合がときどきあります。 | |
719 | ||
1048 | シェルでは、リダイレクトをするときにファイル記述子番号の前に | |
720 | ||
1049 | アンパサンドを置きます。 | |
1050 | 例えば C<< 2>&1 >> は、記述子 2 (これは Perl では STDERR) を | |
1051 | 記述子 1 (これは Perl では普通は STDOUT) にリダイレクトします。 | |
1052 | 同じことは Perl でも基本的には真です: アンパサンドで始まるファイル名は、 | |
1053 | それが数値ならファイル記述子、文字列ならファイルハンドルとして | |
1054 | 扱われます。 | |
721 | 1055 | |
1056 | open(SAVEOUT, ">&SAVEERR") || die "couldn't dup SAVEERR: $!"; | |
1057 | open(MHCONTEXT, "<&4") || die "couldn't dup fd4: $!"; | |
1058 | ||
722 | 1059 | =begin original |
723 | 1060 | |
724 | ||
1061 | That means that if a function is expecting a filename, but you don't | |
725 | ||
1062 | want to give it a filename because you already have the file open, you | |
726 | ||
1063 | can just pass the filehandle with a leading ampersand. It's best to | |
727 | ||
1064 | use a fully qualified handle though, just in case the function happens | |
1065 | to be in a different package: | |
728 | 1066 | |
729 | 1067 | =end original |
730 | 1068 | |
731 | ||
1069 | これは、もし関数がファイル名を想定しているけれども、既にファイルは | |
732 | ||
1070 | 開いているのでファイル名を渡したくない場合、単に先頭にアンパサンドを | |
733 | ||
1071 | 付けたファイルハンドルを渡せるということを意味します。 | |
734 | ||
1072 | しかし、万が一関数がたまたま違うパッケージだったときのために、完全修飾した | |
1073 | ハンドルを渡すのが最善です: | |
735 | 1074 | |
736 | o | |
1075 | somefunction("&main::LOGFILE"); | |
737 | or die "Couldn't open a pipe into cat: $!"; | |
738 | 1076 | |
739 | | |
1077 | =begin original | |
740 | ||
1079 | This way if somefunction() is planning on opening its argument, it can | |
1080 | just use the already opened handle. This differs from passing a handle, | |
1081 | because with a handle, you don't open the file. Here you have something | |
1082 | you can pass to open. | |
1083 | ||
1084 | =end original | |
1085 | ||
1086 | この方法により、somefunction() が引数の値を開いた場合、 | |
1087 | 単に既に開いているハンドルを使えます。 | |
1088 | これはハンドルを渡すのとは違います; なぜならハンドルではファイルを | |
1089 | 開かないからです。 | |
1090 | こちらでは開くときに指定できるものが指定できます。 | |
1091 | ||
1092 | =begin original | |
1093 | ||
1094 | If you have one of those tricky, newfangled I/O objects that the C++ | |
1095 | folks are raving about, then this doesn't work because those aren't a | |
1096 | proper filehandle in the native Perl sense. You'll have to use fileno() | |
1097 | to pull out the proper descriptor number, assuming you can: | |
1098 | ||
1099 | =end original | |
1100 | ||
1101 | もし、C++ 民が夢中になっているような巧妙で目新しい I/O オブジェクトの一つを | |
1102 | 使っているなら、これらはネイティブな Perl 的に適切なファイルハンドルでは | |
1103 | ないので、上述のような方法は動作しません。 | |
1104 | 適切な記述子番号を得るために fileno() を使う必要があります; それが出来ると | |
1105 | 仮定すれば: | |
1106 | ||
1107 | use IO::Socket; | |
1108 | $handle = IO::Socket::INET->new("www.perl.com:80"); | |
1109 | $fd = $handle->fileno; | |
1110 | somefunction("&$fd"); # not an indirect function call | |
1111 | ||
1112 | =begin original | |
1113 | ||
1114 | It can be easier (and certainly will be faster) just to use real | |
1115 | filehandles though: | |
1116 | ||
1117 | =end original | |
1118 | ||
1119 | しかし、単に普通のファイルハンドルを使う方が簡単でしょう | |
1120 | (そして確実に高速です): | |
1121 | ||
1122 | use IO::Socket; | |
1123 | local *REMOTE = IO::Socket::INET->new("www.perl.com:80"); | |
1124 | die "can't connect" unless defined(fileno(REMOTE)); | |
1125 | somefunction("&main::REMOTE"); | |
1126 | ||
1127 | =begin original | |
1128 | ||
1129 | If the filehandle or descriptor number is preceded not just with a simple | |
1130 | "&" but rather with a "&=" combination, then Perl will not create a | |
1131 | completely new descriptor opened to the same place using the dup(2) | |
1132 | system call. Instead, it will just make something of an alias to the | |
1133 | existing one using the fdopen(3S) library call. This is slightly more | |
1134 | parsimonious of systems resources, although this is less a concern | |
1135 | these days. Here's an example of that: | |
1136 | ||
1137 | =end original | |
1138 | ||
1139 | もしファイルハンドルや記述子番号の前にあるのが単なる "&" ではなく "&=" の | |
1140 | 組み合わせの場合、Perl は dup(2) システムコールを使って同じ場所で開いた | |
1141 | 完全に新しい記述子は作りません。 | |
1142 | 代わりに、fdopen(3S) ライブラリコールを使ってすでにある記述子の別名的な | |
1143 | ものを作ります。 | |
1144 | これはシステムのリソースを少しケチることが出来ますが、最近ではこれは | |
1145 | あまり関心を持たれなくなりました。 | |
1146 | 以下はこの例です: | |
1147 | ||
1148 | $fd = $ENV{"MHCONTEXTFD"}; | |
1149 | open(MHCONTEXT, "<&=$fd") or die "couldn't fdopen $fd: $!"; | |
1150 | ||
1151 | =begin original | |
1152 | ||
1153 | If you're using magic C<< <ARGV> >>, you could even pass in as a | |
1154 | command line argument in @ARGV something like C<"<&=$MHCONTEXTFD">, | |
1155 | but we've never seen anyone actually do this. | |
1156 | ||
1157 | =end original | |
1158 | ||
1159 | もしマジカルな C<< <ARGV> >> を使っているなら、C<"<&=$MHCONTEXTFD"> の | |
1160 | ような感じで @ARGV 内のコマンドライン引数として渡すことすら可能ですが、 | |
1161 | 実際にこれをしている人を見たことはありません。 | |
1162 | ||
1163 | =head2 Dispelling the Dweomer | |
1164 | ||
1165 | (魔法を解く) | |
1166 | ||
1167 | =begin original | |
1168 | ||
1169 | Perl is more of a DWIMmer language than something like Java--where DWIM | |
1170 | is an acronym for "do what I mean". But this principle sometimes leads | |
1171 | to more hidden magic than one knows what to do with. In this way, Perl | |
1172 | is also filled with I<dweomer>, an obscure word meaning an enchantment. | |
1173 | Sometimes, Perl's DWIMmer is just too much like dweomer for comfort. | |
1174 | ||
1175 | =end original | |
1176 | ||
1177 | Perl は、Java のような言語よりも「空気を読む」(DWIM)言語です -- | |
1178 | DWIM とは "do what I mean" の略です。 | |
1179 | しかし、この原則は時々利用者が知っている以上の隠れた動作をすることが | |
1180 | あります。 | |
1181 | こんな風に、Perl は (魔法を意味する不明確な単語である) I<dweomer> にも | |
1182 | 満ちています。 | |
1183 | 時々、Perl の空気の読み方は快適さのために魔法のようになります。 | |
1184 | ||
1185 | =begin original | |
1186 | ||
1187 | If magic C<open> is a bit too magical for you, you don't have to turn | |
1188 | to C<sysopen>. To open a file with arbitrary weird characters in | |
1189 | it, it's necessary to protect any leading and trailing whitespace. | |
1190 | Leading whitespace is protected by inserting a C<"./"> in front of a | |
1191 | filename that starts with whitespace. Trailing whitespace is protected | |
1192 | by appending an ASCII NUL byte (C<"\0">) at the end of the string. | |
1193 | ||
1194 | =end original | |
1195 | ||
1196 | もしマジカルな C<open> があなたにとってちょっとマジカルすぎるとしても、 | |
1197 | C<sysopen> にまで戻る必要はありません。 | |
1198 | ファイル名にどんな変な文字が含まれているファイルでも開くためには、 | |
1199 | 先頭と末尾の空白を保護する必要があります。 | |
1200 | 先頭の空白は、空白で始まるファイル名の前に C<"./"> を挿入することで | |
1201 | 保護します。 | |
1202 | 末尾の空白は、文字列の末尾に ASCII NUL バイト (C<"\0">) を | |
1203 | 追加することで保護します。 | |
1204 | ||
1205 | $file =~ s#^(\s)#./$1#; | |
1206 | open(FH, "< $file\0") || die "can't open $file: $!"; | |
1207 | ||
1208 | =begin original | |
1209 | ||
1210 | This assumes, of course, that your system considers dot the current | |
1211 | working directory, slash the directory separator, and disallows ASCII | |
1212 | NULs within a valid filename. Most systems follow these conventions, | |
1213 | including all POSIX systems as well as proprietary Microsoft systems. | |
1214 | The only vaguely popular system that doesn't work this way is the | |
1215 | "Classic" Macintosh system, which uses a colon where the rest of us | |
1216 | use a slash. Maybe C<sysopen> isn't such a bad idea after all. | |
1217 | ||
1218 | =end original | |
1219 | ||
1220 | これはもちろん、あなたのシステムが "." をカレントディレクトリ、 | |
1221 | "/" をディレクトリの区切りとして扱い、ASCII NUL をファイル名として | |
1222 | 認めていないということを仮定しています。 | |
1223 | 全ての POSIX システムとプロプリエタリの Microsoft システムを含む、 | |
1224 | ほとんどのシステムはこの慣例に従っています。 | |
1225 | これに従わない、一般的に有名な唯一のシステムは | |
1226 | "Classic" Macintosh システムです; これは他のシステムが "/" を | |
1227 | 使っているところで ":" を使います。 | |
1228 | おそらく、とにかく C<sysopen> を使うということはそれほど悪い考えでは | |
1229 | ありません。 | |
1230 | ||
1231 | =begin original | |
1232 | ||
1233 | If you want to use C<< <ARGV> >> processing in a totally boring | |
1234 | and non-magical way, you could do this first: | |
1235 | ||
1236 | =end original | |
1237 | ||
1238 | もし、C<< <ARGV> >> の処理を、本当に退屈かつマジカルでない方法で | |
1239 | 行いたいなら、まず以下のようにできます: | |
1240 | ||
1241 | # "Sam sat on the ground and put his head in his hands. | |
1242 | # 'I wish I had never come here, and I don't want to see | |
1243 | # no more magic,' he said, and fell silent." | |
1244 | for (@ARGV) { | |
1245 | s#^([^./])#./$1#; | |
1246 | $_ .= "\0"; | |
1247 | } | |
1248 | while (<>) { | |
1249 | # now process $_ | |
1250 | } | |
1251 | ||
1252 | =begin original | |
1253 | ||
1254 | But be warned that users will not appreciate being unable to use "-" | |
1255 | to mean standard input, per the standard convention. | |
1256 | ||
1257 | =end original | |
1258 | ||
1259 | 但し、ユーザーは、標準入力を意味するために "-" を使うという一般的な | |
1260 | 慣習が使えないということを喜ばないだろうということは | |
1261 | 警告しておきます。 | |
1262 | ||
1263 | =head2 Paths as Opens | |
1264 | ||
1265 | (open にパスを) | |
1266 | ||
1267 | =begin original | |
1268 | ||
1269 | You've probably noticed how Perl's C<warn> and C<die> functions can | |
1270 | produce messages like: | |
1271 | ||
1272 | =end original | |
1273 | ||
1274 | どうやって Perl の C<warn> 関数と C<die> 関数が以下のようなメッセージを | |
1275 | 生成するかに気付いたでしょう: | |
1276 | ||
1277 | Some warning at scriptname line 29, <FH> line 7. | |
1278 | ||
1279 | =begin original | |
1280 | ||
1281 | That's because you opened a filehandle FH, and had read in seven records | |
1282 | from it. But what was the name of the file, rather than the handle? | |
1283 | ||
1284 | =end original | |
1285 | ||
1286 | これは、あなたがファイルハンドル FH を開いて、そこから 7 レコードを | |
1287 | 読み込んだからです。 | |
1288 | しかし、ハンドルではなく、ファイル名はどうでしょう? | |
1289 | ||
1290 | =begin original | |
1291 | ||
1292 | If you aren't running with C<strict refs>, or if you've turned them off | |
1293 | temporarily, then all you have to do is this: | |
1294 | ||
1295 | =end original | |
1296 | ||
1297 | もし C<strict refs> を有効にしていないか、一時的に無効にしているなら、 | |
1298 | する必要があるのは以下のことだけです: | |
1299 | ||
1300 | open($path, "< $path") || die "can't open $path: $!"; | |
1301 | while (<$path>) { | |
1302 | # whatever | |
1303 | } | |
1304 | ||
1305 | =begin original | |
1306 | ||
1307 | Since you're using the pathname of the file as its handle, | |
1308 | you'll get warnings more like | |
1309 | ||
1310 | =end original | |
1311 | ||
1312 | ファイルのパス名をハンドルとして使っているので、以下のような警告が | |
1313 | 出ます | |
1314 | ||
1315 | Some warning at scriptname line 29, </etc/motd> line 7. | |
1316 | ||
1317 | =head2 Single Argument Open | |
1318 | ||
1319 | (1 引数の open) | |
1320 | ||
1321 | =begin original | |
1322 | ||
1323 | Remember how we said that Perl's open took two arguments? That was a | |
1324 | passive prevarication. You see, it can also take just one argument. | |
1325 | If and only if the variable is a global variable, not a lexical, you | |
1326 | can pass C<open> just one argument, the filehandle, and it will | |
1327 | get the path from the global scalar variable of the same name. | |
1328 | ||
1329 | =end original | |
1330 | ||
1331 | Perl の open は 2 引数を取ると言ったことを覚えていますか? | |
1332 | これは消極的なごまかしです。 | |
1333 | ほら、単に 1 引数を取ることもできます。 | |
1334 | 変数がレキシカルではなくグローバルな変数の場合にのみ、C<open> に | |
1335 | 1 引数だけ(ファイルハンドル)を渡すことができます; こうすると、 | |
1336 | 同じ名前を持つグローバルなスカラ変数からパスを取ります。 | |
1337 | ||
1338 | $FILE = "/etc/motd"; | |
1339 | open FILE or die "can't open $FILE: $!"; | |
1340 | while (<FILE>) { | |
1341 | # whatever | |
1342 | } | |
1343 | ||
1344 | =begin original | |
1345 | ||
1346 | Why is this here? Someone has to cater to the hysterical porpoises. | |
1347 | It's something that's been in Perl since the very beginning, if not | |
1348 | before. | |
1349 | ||
1350 | =end original | |
1351 | ||
1352 | どうしてこれはここなんでしょう? | |
1353 | 誰かがヒステリックなネズミイルカの要求を満たす必要があります。 | |
1354 | これは(遅くとも)非常に初期から Perl にあります。 | |
1355 | ||
1356 | =head2 Playing with STDIN and STDOUT | |
1357 | ||
1358 | (STDIN と STDOUT を扱う) | |
1359 | ||
1360 | =begin original | |
1361 | ||
1362 | One clever move with STDOUT is to explicitly close it when you're done | |
1363 | with the program. | |
1364 | ||
1365 | =end original | |
1366 | ||
1367 | STDOUT に関する一つの利口な行動は、プログラムの終了時に | |
1368 | 明示的に閉じることです。 | |
1369 | ||
1370 | END { close(STDOUT) || die "can't close stdout: $!" } | |
1371 | ||
1372 | =begin original | |
1373 | ||
1374 | If you don't do this, and your program fills up the disk partition due | |
1375 | to a command line redirection, it won't report the error exit with a | |
1376 | failure status. | |
1377 | ||
1378 | =end original | |
1379 | ||
1380 | これをしないままで、このプログラムがコマンドラインリダイレクトによって | |
1381 | ディスクをいっぱいにしてしまっても、失敗状態でエラー終了しません。 | |
1382 | ||
1383 | =begin original | |
1384 | ||
1385 | You don't have to accept the STDIN and STDOUT you were given. You are | |
1386 | welcome to reopen them if you'd like. | |
1387 | ||
1388 | =end original | |
1389 | ||
1390 | 与えられた STDIN と STDOUT を受け入れる必要はありません。 | |
1391 | もし望むなら、これらを開き直せます。 | |
1392 | ||
1393 | open(STDIN, "< datafile") | |
1394 | || die "can't open datafile: $!"; | |
1395 | ||
1396 | open(STDOUT, "> output") | |
1397 | || die "can't open output: $!"; | |
1398 | ||
1399 | =begin original | |
1400 | ||
1401 | And then these can be accessed directly or passed on to subprocesses. | |
1402 | This makes it look as though the program were initially invoked | |
1403 | with those redirections from the command line. | |
1404 | ||
1405 | =end original | |
1406 | ||
1407 | それからこれらは直接アクセスしたり子プロセスに渡したりできます。 | |
1408 | これらは、プログラムの起動時にコマンドラインからリダイレクトが | |
1409 | 与えられたかのように動作します。 | |
1410 | ||
1411 | =begin original | |
1412 | ||
1413 | It's probably more interesting to connect these to pipes. For example: | |
1414 | ||
1415 | =end original | |
1416 | ||
1417 | これらをパイプにつなぐ方がより興味深いでしょう。 | |
1418 | 例えば: | |
1419 | ||
1420 | $pager = $ENV{PAGER} || "(less || more)"; | |
1421 | open(STDOUT, "| $pager") | |
1422 | || die "can't fork a pager: $!"; | |
1423 | ||
1424 | =begin original | |
1425 | ||
1426 | This makes it appear as though your program were called with its stdout | |
1427 | already piped into your pager. You can also use this kind of thing | |
1428 | in conjunction with an implicit fork to yourself. You might do this | |
1429 | if you would rather handle the post processing in your own program, | |
1430 | just in a different process: | |
1431 | ||
1432 | =end original | |
1433 | ||
1434 | これによって、プログラムの標準出力がが既にページャとパイプで | |
1435 | つながれているかのように見えます。 | |
1436 | このようなことはまた、自分自身を暗黙に fork したものと結合するためにも | |
1437 | 使えます。 | |
1438 | 自分自身のプログラムの別のプロセスでで後処理を扱いたい場合、 | |
1439 | 以下のようにできます: | |
1440 | ||
1441 | head(100); | |
1442 | while (<>) { | |
1443 | print; | |
1444 | } | |
1445 | ||
1446 | sub head { | |
1447 | my $lines = shift || 20; | |
1448 | return if $pid = open(STDOUT, "|-"); # return if parent | |
1449 | die "cannot fork: $!" unless defined $pid; | |
1450 | while (<STDIN>) { | |
1451 | last if --$lines < 0; | |
1452 | print; | |
1453 | } | |
1454 | exit; | |
1455 | } | |
1456 | ||
1457 | =begin original | |
1458 | ||
1459 | This technique can be applied to repeatedly push as many filters on your | |
1460 | output stream as you wish. | |
1461 | ||
1462 | =end original | |
1463 | ||
1464 | このテクニックは、繰り返しプッシュすることで、出力ストリームに好きなだけ | |
1465 | 多くのフィルタを適用できます。 | |
1466 | ||
1467 | =head1 Other I/O Issues | |
1468 | ||
1469 | (その他の I/O 関連の話題) | |
1470 | ||
1471 | =begin original | |
1472 | ||
1473 | These topics aren't really arguments related to C<open> or C<sysopen>, | |
1474 | but they do affect what you do with your open files. | |
1475 | ||
1476 | =end original | |
1477 | ||
1478 | これらの話題は実際には C<open> や C<sysopen> に関連したものではありませんが、 | |
1479 | ファイルを開くときに行うことに影響を与えます。 | |
1480 | ||
1481 | =head2 Opening Non-File Files | |
1482 | ||
1483 | (ファイルでないファイルを開く) | |
1484 | ||
1485 | =begin original | |
1486 | ||
1487 | When is a file not a file? Well, you could say when it exists but | |
1488 | isn't a plain file. We'll check whether it's a symbolic link first, | |
1489 | just in case. | |
1490 | ||
1491 | =end original | |
1492 | ||
1493 | ファイルがファイルでないときは? | |
1494 | えっと、プレーンファイルでないもののとき、と言いたいんですよね。 | |
1495 | まず、念のために、それがシンボリックリンクかどうかを調べます。 | |
1496 | ||
1497 | if (-l $file || ! -f _) { | |
1498 | print "$file is not a plain file\n"; | |
1499 | } | |
1500 | ||
1501 | =begin original | |
1502 | ||
1503 | What other kinds of files are there than, well, files? Directories, | |
1504 | symbolic links, named pipes, Unix-domain sockets, and block and character | |
1505 | devices. Those are all files, too--just not I<plain> files. This isn't | |
1506 | the same issue as being a text file. Not all text files are plain files. | |
1507 | Not all plain files are text files. That's why there are separate C<-f> | |
1508 | and C<-T> file tests. | |
1509 | ||
1510 | =end original | |
1511 | ||
1512 | えーと、ファイルの他にどんな種類のファイルがあるのでしょう? | |
1513 | ディレクトリ、シンボリックリンク、名前付きパイプ、Unix ドメインソケット、 | |
1514 | キャラクタデバイス、ブロックデバイスです。 | |
1515 | これらも全てファイルです -- 単に I<プレーン> ファイルではないと | |
1516 | いうだけです。 | |
1517 | これはテキストファイルと同じ問題ではありません。 | |
1518 | 全てのテキストファイルがプレーンファイルではありません。 | |
1519 | 全てのプレーンファイルがテキストファイルではありません。 | |
1520 | これが、C<-f> と C<-T> のファイルテストが分離している理由です。 | |
1521 | ||
1522 | =begin original | |
1523 | ||
1524 | To open a directory, you should use the C<opendir> function, then | |
1525 | process it with C<readdir>, carefully restoring the directory | |
1526 | name if necessary: | |
1527 | ||
1528 | =end original | |
1529 | ||
1530 | ディレクトリを開くには、C<opendir> 関数を使って、それから | |
1531 | C<readdir> で処理します; もし必要なら注意深くディレクトリ名を復元します: | |
1532 | ||
1533 | opendir(DIR, $dirname) or die "can't opendir $dirname: $!"; | |
1534 | while (defined($file = readdir(DIR))) { | |
1535 | # do something with "$dirname/$file" | |
741 | 1536 | } |
1537 | closedir(DIR); | |
742 | 1538 | |
743 | 1539 | =begin original |
744 | 1540 | |
745 | ||
1541 | If you want to process directories recursively, it's better to use the | |
746 | ||
1542 | File::Find module. For example, this prints out all files recursively | |
747 | ||
1543 | and adds a slash to their names if the file is a directory. | |
748 | basic function of C<print>-ing data to it. | |
749 | 1544 | |
750 | 1545 | =end original |
751 | 1546 | |
752 | ||
1547 | ディレクトリを再帰的に処理したい場合は、File::Find モジュールを使った方が | |
753 | ||
1548 | いいでしょう。 | |
754 | ||
1549 | 例えば、これは全てのファイルを再帰的に表示して、もしファイルが | |
755 | ||
1550 | ディレクトリの場合は末尾にスラッシュを追加します。 | |
756 | 書き込み専用の普通のファイルハンドルを使うのと同じようにこれを使えます。 | |
757 | 1551 | |
1552 | @ARGV = qw(.) unless @ARGV; | |
1553 | use File::Find; | |
1554 | find sub { print $File::Find::name, -d && '/', "\n" }, @ARGV; | |
1555 | ||
758 | 1556 | =begin original |
759 | 1557 | |
760 | ||
1558 | This finds all bogus symbolic links beneath a particular directory: | |
761 | pipe to, sets up C<cat> to redirect its output via that C<< ">" >> | |
762 | symbol into the file C<numbered.txt>. This can start to look a little | |
763 | tricky, because that same symbol would have meant something | |
764 | entirely different had it showed it in the second argument to C<open>! | |
765 | But here in the third argument, it's simply part of the shell command that | |
766 | Perl will open the pipe into, and Perl itself doesn't invest any special | |
767 | meaning to it. | |
768 | 1559 | |
769 | 1560 | =end original |
770 | 1561 | |
771 | ||
1562 | 以下は、特定のディレクトリ以下から偽のシンボリックリンクを全て探します: | |
772 | C<cat> の出力を C<< ">" >> 記号を使ってファイル C<numbered.txt> に | |
773 | リダイレクトするように指定していることに注意してください。 | |
774 | これは最初は少しおかしく見えるかもしれません; | |
775 | この同じ記号は、C<open> の 2 番目の引数では全く違うものを意味するからです! | |
776 | しかし、ここ 3 番目の引数では、これは単に Perl がパイプを開く | |
777 | シェルコマンドの一部であり、Perl 自身はこれに何の特別な意味も与えません。 | |
778 | 1563 | |
779 | ||
1564 | find sub { print "$File::Find::name\n" if -l && !-e }, $dir; | |
780 | 1565 | |
781 | ||
1566 | =begin original | |
782 | 1567 | |
1568 | As you see, with symbolic links, you can just pretend that it is | |
1569 | what it points to. Or, if you want to know I<what> it points to, then | |
1570 | C<readlink> is called for: | |
1571 | ||
1572 | =end original | |
1573 | ||
1574 | 上述したように、シンボリックリンクの場合、単にそれが指しているもの振りを | |
1575 | することができます。 | |
1576 | あるいは、もしそれが I<何を> 指しているのかを知りたい場合は、 | |
1577 | C<readlink> を呼び出します: | |
1578 | ||
1579 | if (-l $file) { | |
1580 | if (defined($whither = readlink($file))) { | |
1581 | print "$file points to $whither\n"; | |
1582 | } else { | |
1583 | print "$file points nowhere: $!\n"; | |
1584 | } | |
1585 | } | |
1586 | ||
1587 | =head2 Opening Named Pipes | |
1588 | ||
1589 | (名前付きパイプを開く) | |
1590 | ||
783 | 1591 | =begin original |
784 | 1592 | |
785 | ||
1593 | Named pipes are a different matter. You pretend they're regular files, | |
786 | ||
1594 | but their opens will normally block until there is both a reader and | |
787 | ||
1595 | a writer. You can read more about them in L<perlipc/"Named Pipes">. | |
788 | ||
1596 | Unix-domain sockets are rather different beasts as well; they're | |
789 | ||
1597 | described in L<perlipc/"Unix-Domain TCP Clients and Servers">. | |
790 | 1598 | |
791 | 1599 | =end original |
792 | 1600 | |
793 | パイプ | |
1601 | 名前付きパイプは別の問題です。 | |
794 | ||
1602 | これらは普通のファイルのように振る舞いますが、この open は普通 | |
795 | ||
1603 | 読み込み側と書き込み側の両方ができるまでブロックされます。 | |
796 | ||
1604 | これらについては L<perlipc/"Named Pipes"> でより多くのことを | |
797 | ||
1605 | 読むことができます。 | |
1606 | Unix ドメインソケットは同様にやや違うものです; | |
1607 | これらは L<perlipc/"Unix-Domain TCP Clients and Servers"> に | |
1608 | 記述されています。 | |
798 | 1609 | |
799 | ||
1610 | =begin original | |
800 | or die "Couldn't open a pipe into sort: $!"; | |
801 | 1611 | |
1612 | When it comes to opening devices, it can be easy and it can be tricky. | |
1613 | We'll assume that if you're opening up a block device, you know what | |
1614 | you're doing. The character devices are more interesting. These are | |
1615 | typically used for modems, mice, and some kinds of printers. This is | |
1616 | described in L<perlfaq8/"How do I read and write the serial port?"> | |
1617 | It's often enough to open them carefully: | |
1618 | ||
1619 | =end original | |
1620 | ||
1621 | デバイスを開くときは、簡単にもなりますしトリッキーにもなります。 | |
1622 | ブロックデバイスを開こうとしているなら、何をしようとしているのか | |
1623 | 分かっていることを仮定します。 | |
1624 | キャラクタデバイスはもっと興味深いです。 | |
1625 | これらは典型的にはモデム、マウス、ある種のプリンタのために使われます。 | |
1626 | これは L<perlfaq8/"How do I read and write the serial port?"> に | |
1627 | 記述されています。 | |
1628 | しばしば慎重に開くだけで充分です: | |
1629 | ||
1630 | sysopen(TTYIN, "/dev/ttyS1", O_RDWR | O_NDELAY | O_NOCTTY) | |
1631 | # (O_NOCTTY no longer needed on POSIX systems) | |
1632 | or die "can't open /dev/ttyS1: $!"; | |
1633 | open(TTYOUT, "+>&TTYIN") | |
1634 | or die "can't dup TTYIN: $!"; | |
1635 | ||
1636 | $ofh = select(TTYOUT); $| = 1; select($ofh); | |
1637 | ||
1638 | print TTYOUT "+++at\015"; | |
1639 | $answer = <TTYIN>; | |
1640 | ||
802 | 1641 | =begin original |
803 | 1642 | |
804 | W | |
1643 | With descriptors that you haven't opened using C<sysopen>, such as | |
805 | ||
1644 | sockets, you can set them to be non-blocking using C<fcntl>: | |
806 | special characters within the command's argument list, which might | |
807 | overwise have unwanted effects. This can make for safer, less | |
808 | error-prone C<open> calls, useful in cases such as passing in variables | |
809 | as arguments, or even just referring to filenames with spaces in them. | |
810 | 1645 | |
811 | 1646 | =end original |
812 | 1647 | |
813 | ||
1648 | ソケットのように、C<sysopen> を使わずに開いた記述子の場合は、 | |
814 | ||
1649 | C<fcntl> を使って非ブロックモードに設定できます: | |
815 | シェルはコマンド路の引数リストの中の特殊文字を解釈しようとはしません; | |
816 | さもなければ望まない効果を生むことがあります。 | |
817 | これはより安全で、C<open> 呼び出しの誤りを減らし、 | |
818 | 引数として変数の内容を渡すような場合に有用で、 | |
819 | 単に空白を含むファイルを参照する場合にも安全です。 | |
820 | 1650 | |
1651 | use Fcntl; | |
1652 | my $old_flags = fcntl($handle, F_GETFL, 0) | |
1653 | or die "can't get flags: $!"; | |
1654 | fcntl($handle, F_SETFL, $old_flags | O_NONBLOCK) | |
1655 | or die "can't set non blocking: $!"; | |
1656 | ||
821 | 1657 | =begin original |
822 | 1658 | |
823 | ||
1659 | Rather than losing yourself in a morass of twisting, turning C<ioctl>s, | |
824 | ||
1660 | all dissimilar, if you're going to manipulate ttys, it's best to | |
825 | ||
1661 | make calls out to the stty(1) program if you have it, or else use the | |
826 | ||
1662 | portable POSIX interface. To figure this all out, you'll need to read the | |
827 | ||
1663 | termios(3) manpage, which describes the POSIX interface to tty devices, | |
828 | ||
1664 | and then L<POSIX>, which describes Perl's interface to POSIX. There are | |
1665 | also some high-level modules on CPAN that can help you with these games. | |
1666 | Check out Term::ReadKey and Term::ReadLine. | |
829 | 1667 | |
830 | 1668 | =end original |
831 | 1669 | |
832 | し | |
1670 | もし tty を操作しようとしているなら、全く異なる C<ioctl> の泥沼に | |
833 | ||
1671 | 迷い込むのではなく、もし stty(1) プログラムがあるならこれを呼び出して、 | |
834 | ||
1672 | さもなければ移植性のある POSIX インターフェースを使うのが最善です。 | |
835 | この | |
1673 | これらのこと全てを理解するには、まず tty デバイスへの POSIX | |
836 | ||
1674 | インターフェースについて記述している termios(3) man ページを読んで、次に | |
837 | ||
1675 | POSIX への Perl のインターフェースについて記述している L<POSIX> を | |
1676 | 読む必要があります。 | |
1677 | これらのものを扱う助けになるような高レベルモジュールも CPAN にあります。 | |
1678 | Term::ReadKey と Term::ReadLine を調べてください。 | |
838 | 1679 | |
1680 | =head2 Opening Sockets | |
1681 | ||
1682 | (ソケットを開く) | |
1683 | ||
839 | 1684 | =begin original |
840 | 1685 | |
841 | ||
1686 | What else can you open? To open a connection using sockets, you won't use | |
842 | ||
1687 | one of Perl's two open functions. See | |
843 | ||
1688 | L<perlipc/"Sockets: Client/Server Communication"> for that. Here's an | |
844 | ||
1689 | example. Once you have it, you can use FH as a bidirectional filehandle. | |
845 | 1690 | |
846 | 1691 | =end original |
847 | 1692 | |
848 | ||
1693 | 他の何を開けるの? | |
849 | ||
1694 | ソケットを使った接続を開くには、Perl の 2 つの open 関数のどちらも | |
850 | ||
1695 | 使いません。 | |
851 | ||
1696 | そのためには L<perlipc/"Sockets: Client/Server Communication"> を | |
1697 | 参照してください。 | |
1698 | 以下は例です。 | |
1699 | これを実行すると、FH を双方向ファイルハンドルとして使えます。 | |
852 | 1700 | |
853 | ||
1701 | use IO::Socket; | |
1702 | local *FH = IO::Socket::INET->new("www.perl.com:80"); | |
854 | 1703 | |
855 | 1704 | =begin original |
856 | 1705 | |
857 | ||
1706 | For opening up a URL, the LWP modules from CPAN are just what | |
858 | ||
1707 | the doctor ordered. There's no filehandle interface, but | |
859 | ||
1708 | it's still easy to get the contents of a document: | |
860 | 1709 | |
861 | 1710 | =end original |
862 | 1711 | |
863 | L | |
1712 | URL を開くには、CPAN にある LWP モジュールがぴったりです。 | |
864 | ||
1713 | ファイルハンドルのインターフェースはないですが、 | |
865 | ||
1714 | それでも簡単に文書の中身を得られます: | |
866 | 1715 | |
1716 | use LWP::Simple; | |
1717 | $doc = get('http://www.linpro.no/lwp/'); | |
1718 | ||
1719 | =head2 Binary Files | |
1720 | ||
1721 | (バイナリファイル) | |
1722 | ||
1723 | =begin original | |
1724 | ||
1725 | On certain legacy systems with what could charitably be called terminally | |
1726 | convoluted (some would say broken) I/O models, a file isn't a file--at | |
1727 | least, not with respect to the C standard I/O library. On these old | |
1728 | systems whose libraries (but not kernels) distinguish between text and | |
1729 | binary streams, to get files to behave properly you'll have to bend over | |
1730 | backwards to avoid nasty problems. On such infelicitous systems, sockets | |
1731 | and pipes are already opened in binary mode, and there is currently no | |
1732 | way to turn that off. With files, you have more options. | |
1733 | ||
1734 | =end original | |
1735 | ||
1736 | 最終的に (壊れていると言われる) I/O モデルに巻き込まれると寛大にも | |
1737 | 呼ばれるある種の古いシステムでは、ファイルはファイルではありません -- | |
1738 | 少なくとも C 標準 I/O ライブラリという観点では。 | |
1739 | (カーネルではなく)ライブラリがテキストストリームとバイナリストリームを | |
1740 | 区別するような古いシステムでは、適切に振る舞うようにファイルを | |
1741 | 取得するためには、不愉快な問題を避けるために懸命な努力が必要です。 | |
1742 | このような不幸なシステムでは、ソケットとパイプは既にバイナリモードで | |
1743 | 開いていて、今のところこれをオフにする方法はありません。 | |
1744 | ファイルに対しては、もっと選択肢があります。 | |
1745 | ||
1746 | =begin original | |
1747 | ||
1748 | Another option is to use the C<binmode> function on the appropriate | |
1749 | handles before doing regular I/O on them: | |
1750 | ||
1751 | =end original | |
1752 | ||
1753 | もう一つの選択肢は、通常の I/O を行う前に、適切なファイルハンドルに | |
1754 | C<binmode> 関数を使うことです: | |
1755 | ||
1756 | binmode(STDIN); | |
1757 | binmode(STDOUT); | |
1758 | while (<STDIN>) { print } | |
1759 | ||
1760 | =begin original | |
1761 | ||
1762 | Passing C<sysopen> a non-standard flag option will also open the file in | |
1763 | binary mode on those systems that support it. This is the equivalent of | |
1764 | opening the file normally, then calling C<binmode> on the handle. | |
1765 | ||
1766 | =end original | |
1767 | ||
1768 | C<sysopen> に非標準フラグオプションを渡すことでも、そのような | |
1769 | システムでバイナリモードでファイルを開けます。 | |
1770 | これは、ファイルを普通に開いてから、ハンドルに対して C<binmode> を | |
1771 | 呼び出すのと等価です。 | |
1772 | ||
1773 | sysopen(BINDAT, "records.data", O_RDWR | O_BINARY) | |
1774 | || die "can't open records.data: $!"; | |
1775 | ||
1776 | =begin original | |
1777 | ||
1778 | Now you can use C<read> and C<print> on that handle without worrying | |
1779 | about the non-standard system I/O library breaking your data. It's not | |
1780 | a pretty picture, but then, legacy systems seldom are. CP/M will be | |
1781 | with us until the end of days, and after. | |
1782 | ||
1783 | =end original | |
1784 | ||
1785 | これで、非標準システム I/O ライブラリがデータを壊す心配なしに | |
1786 | ハンドルに対して C<read> と C<print> を使えるようになりました。 | |
1787 | これは美しい形ではありませんが、レガシーシステムとは大抵そういうものです。 | |
1788 | CP/M は世界が終わるまで(そしてその後も)我々と共にあるでしょう。 | |
1789 | ||
1790 | =begin original | |
1791 | ||
1792 | On systems with exotic I/O systems, it turns out that, astonishingly | |
1793 | enough, even unbuffered I/O using C<sysread> and C<syswrite> might do | |
1794 | sneaky data mutilation behind your back. | |
1795 | ||
1796 | =end original | |
1797 | ||
1798 | 風変わりな I/O システムを持つシステムでは、驚いたことに、 | |
1799 | C<sysread> や C<syswrite> を使ったバッファリングしない I/O でさえも | |
1800 | 背後でこっそりとデータ操作をすることがあります。 | |
1801 | ||
1802 | while (sysread(WHENCE, $buf, 1024)) { | |
1803 | syswrite(WHITHER, $buf, length($buf)); | |
1804 | } | |
1805 | ||
1806 | =begin original | |
1807 | ||
1808 | Depending on the vicissitudes of your runtime system, even these calls | |
1809 | may need C<binmode> or C<O_BINARY> first. Systems known to be free of | |
1810 | such difficulties include Unix, the Mac OS, Plan 9, and Inferno. | |
1811 | ||
1812 | =end original | |
1813 | ||
1814 | 実行させるシステムの紆余曲折具合によっては、これらのシステムコールですら | |
1815 | 最初に C<binmode> や C<O_BINARY> が必要かもしれません。 | |
1816 | このような問題がないと分かっているシステムには Unix, Mac OS, Plan 9, | |
1817 | Inferno などがあります。 | |
1818 | ||
1819 | =head2 File Locking | |
1820 | ||
1821 | (ファイルのロック) | |
1822 | ||
1823 | =begin original | |
1824 | ||
1825 | In a multitasking environment, you may need to be careful not to collide | |
1826 | with other processes who want to do I/O on the same files as you | |
1827 | are working on. You'll often need shared or exclusive locks | |
1828 | on files for reading and writing respectively. You might just | |
1829 | pretend that only exclusive locks exist. | |
1830 | ||
1831 | =end original | |
1832 | ||
1833 | マルチタスク環境では、あなたが触ろうとしているファイルと同じファイルを | |
1834 | 他のプロセスが衝突しないように気をつける必要があります。 | |
1835 | しばしば、ファイルを読み込みまたは書き込みするために、それぞれ | |
1836 | 共有ロックと排他ロックが必要になります。 | |
1837 | あるいは、単に排他ロックしかないような振りをするかもしれません。 | |
1838 | ||
1839 | =begin original | |
1840 | ||
1841 | Never use the existence of a file C<-e $file> as a locking indication, | |
1842 | because there is a race condition between the test for the existence of | |
1843 | the file and its creation. It's possible for another process to create | |
1844 | a file in the slice of time between your existence check and your attempt | |
1845 | to create the file. Atomicity is critical. | |
1846 | ||
1847 | =end original | |
1848 | ||
1849 | 決して、ファイルの存在 C<-e $file> をロック指示に使わないでください; | |
1850 | なぜならファイルの存在のテストとその作成の間に競合条件があるからです。 | |
1851 | 存在チェックとファイル作成のわずかな間に、他のプロセスがファイルを作る | |
1852 | 可能性があります。 | |
1853 | 原子性は危機的です。 | |
1854 | ||
1855 | =begin original | |
1856 | ||
1857 | Perl's most portable locking interface is via the C<flock> function, | |
1858 | whose simplicity is emulated on systems that don't directly support it | |
1859 | such as SysV or Windows. The underlying semantics may affect how | |
1860 | it all works, so you should learn how C<flock> is implemented on your | |
1861 | system's port of Perl. | |
1862 | ||
1863 | =end original | |
1864 | ||
1865 | Perl でのもっとも移植性のあるロックインターフェースは、 | |
1866 | C<flock> 関数によるものです; この単純さは、SysV や Windows のような、 | |
1867 | これに直接対応していないシステムでもエミュレートされています。 | |
1868 | 基礎となる動作はこれがどのように働くかに影響を与えるので、 | |
1869 | あなたが使うシステムの Perl で C<flock> がどのように実装されているかを | |
1870 | 学ぶべきです。 | |
1871 | ||
1872 | =begin original | |
1873 | ||
1874 | File locking I<does not> lock out another process that would like to | |
1875 | do I/O. A file lock only locks out others trying to get a lock, not | |
1876 | processes trying to do I/O. Because locks are advisory, if one process | |
1877 | uses locking and another doesn't, all bets are off. | |
1878 | ||
1879 | =end original | |
1880 | ||
1881 | ファイルロックは、他のプロセスが I/O 操作を行うことからロックするもの | |
1882 | I<ではありません>。 | |
1883 | ファイルロックは、他のプロセスの I/O 操作をロックするのではなく、他の | |
1884 | プロセスがロックを得ようとすることをロックします。 | |
1885 | ロックは勧告的なので、あるプロセスがロックを使っていても、他の | |
1886 | プロセスがロックを使っていなければ、全ては台無しになります。 | |
1887 | ||
1888 | =begin original | |
1889 | ||
1890 | By default, the C<flock> call will block until a lock is granted. | |
1891 | A request for a shared lock will be granted as soon as there is no | |
1892 | exclusive locker. A request for an exclusive lock will be granted as | |
1893 | soon as there is no locker of any kind. Locks are on file descriptors, | |
1894 | not file names. You can't lock a file until you open it, and you can't | |
1895 | hold on to a lock once the file has been closed. | |
1896 | ||
1897 | =end original | |
1898 | ||
1899 | デフォルトでは、C<flock> 呼び出しは、ロックが得られるまでブロックします。 | |
1900 | 共有ロック要求は、誰も排他ロックを持っていない状態になれば直ちに | |
1901 | 受け入れられます。 | |
1902 | 排他ロック要求は、誰もあらゆる種類のロックを守っていない状態になれば | |
1903 | 与えられます。 | |
1904 | ロックはファイル名に対してではなく、ファイル記述子について与えられます。 | |
1905 | ファイルを開かずにファイルをロックすることはできませんし、ファイルを閉じた | |
1906 | 後もロックを持ったままにすることもできません。 | |
1907 | ||
1908 | =begin original | |
1909 | ||
1910 | Here's how to get a blocking shared lock on a file, typically used | |
1911 | for reading: | |
1912 | ||
1913 | =end original | |
1914 | ||
1915 | 以下はファイルに対してブロックする共有ロックを得る方法で、 | |
1916 | 典型的には読み込み時に使われます: | |
1917 | ||
1918 | use 5.004; | |
1919 | use Fcntl qw(:DEFAULT :flock); | |
1920 | open(FH, "< filename") or die "can't open filename: $!"; | |
1921 | flock(FH, LOCK_SH) or die "can't lock filename: $!"; | |
1922 | # now read from FH | |
1923 | ||
1924 | =begin original | |
1925 | ||
1926 | You can get a non-blocking lock by using C<LOCK_NB>. | |
1927 | ||
1928 | =end original | |
1929 | ||
1930 | C<LOCK_NB> を使うことでブロックしないロックも得られます。 | |
1931 | ||
1932 | flock(FH, LOCK_SH | LOCK_NB) | |
1933 | or die "can't lock filename: $!"; | |
1934 | ||
1935 | =begin original | |
1936 | ||
1937 | This can be useful for producing more user-friendly behaviour by warning | |
1938 | if you're going to be blocking: | |
1939 | ||
1940 | =end original | |
1941 | ||
1942 | ブロックするときに警告することで、よりユーザーにやさしい振る舞いを | |
1943 | することは有用です: | |
1944 | ||
1945 | use 5.004; | |
1946 | use Fcntl qw(:DEFAULT :flock); | |
1947 | open(FH, "< filename") or die "can't open filename: $!"; | |
1948 | unless (flock(FH, LOCK_SH | LOCK_NB)) { | |
1949 | $| = 1; | |
1950 | print "Waiting for lock..."; | |
1951 | flock(FH, LOCK_SH) or die "can't lock filename: $!"; | |
1952 | print "got it.\n" | |
1953 | } | |
1954 | # now read from FH | |
1955 | ||
1956 | =begin original | |
1957 | ||
1958 | To get an exclusive lock, typically used for writing, you have to be | |
1959 | careful. We C<sysopen> the file so it can be locked before it gets | |
1960 | emptied. You can get a nonblocking version using C<LOCK_EX | LOCK_NB>. | |
1961 | ||
1962 | =end original | |
1963 | ||
1964 | (典型的には書き込みのために) 排他ロックを得るためには、慎重になる | |
1965 | 必要があります。 | |
1966 | 空なる前にロックするために、ファイルを C<sysopen> で開きます。 | |
1967 | C<LOCK_EX | LOCK_NB> を使った非ブロック版も得られます。 | |
1968 | ||
1969 | use 5.004; | |
1970 | use Fcntl qw(:DEFAULT :flock); | |
1971 | sysopen(FH, "filename", O_WRONLY | O_CREAT) | |
1972 | or die "can't open filename: $!"; | |
1973 | flock(FH, LOCK_EX) | |
1974 | or die "can't lock filename: $!"; | |
1975 | truncate(FH, 0) | |
1976 | or die "can't truncate filename: $!"; | |
1977 | # now write to FH | |
1978 | ||
1979 | =begin original | |
1980 | ||
1981 | Finally, due to the uncounted millions who cannot be dissuaded from | |
1982 | wasting cycles on useless vanity devices called hit counters, here's | |
1983 | how to increment a number in a file safely: | |
1984 | ||
1985 | =end original | |
1986 | ||
1987 | 最後に、アクセスカウンタと呼ばれる無駄で空虚な装置のために CPU パワーを | |
1988 | 無駄遣いすることから逃れられない無慮数百万のために、 | |
1989 | あるファイルの数値を安全に増加させる方法を以下に示します: | |
1990 | ||
1991 | use Fcntl qw(:DEFAULT :flock); | |
1992 | ||
1993 | sysopen(FH, "numfile", O_RDWR | O_CREAT) | |
1994 | or die "can't open numfile: $!"; | |
1995 | # autoflush FH | |
1996 | $ofh = select(FH); $| = 1; select ($ofh); | |
1997 | flock(FH, LOCK_EX) | |
1998 | or die "can't write-lock numfile: $!"; | |
1999 | ||
2000 | $num = <FH> || 0; | |
2001 | seek(FH, 0, 0) | |
2002 | or die "can't rewind numfile : $!"; | |
2003 | print FH $num+1, "\n" | |
2004 | or die "can't write numfile: $!"; | |
2005 | ||
2006 | truncate(FH, tell(FH)) | |
2007 | or die "can't truncate numfile: $!"; | |
2008 | close(FH) | |
2009 | or die "can't close numfile: $!"; | |
2010 | ||
2011 | =head2 IO Layers | |
2012 | ||
2013 | (IO 層) | |
2014 | ||
2015 | =begin original | |
2016 | ||
2017 | In Perl 5.8.0 a new I/O framework called "PerlIO" was introduced. | |
2018 | This is a new "plumbing" for all the I/O happening in Perl; for the | |
2019 | most part everything will work just as it did, but PerlIO also brought | |
2020 | in some new features such as the ability to think of I/O as "layers". | |
2021 | One I/O layer may in addition to just moving the data also do | |
2022 | transformations on the data. Such transformations may include | |
2023 | compression and decompression, encryption and decryption, and transforming | |
2024 | between various character encodings. | |
2025 | ||
2026 | =end original | |
2027 | ||
2028 | Perl 5.8.0 で、"PerlIO" と呼ばれる新しい I/O フレームワークが | |
2029 | 導入されました。 | |
2030 | これは Perl で発生する全ての I/O のための新しい「配管」です; | |
2031 | ほとんど全ての部分では単に今まで通りに動作しますが、 | |
2032 | I/O を「層」として考えるための機能のような、新しい要素も導入されています。 | |
2033 | ある I/O 層は単にデータを移動させるだけでなく、データを変換するかも知れません。 | |
2034 | このような変換には、圧縮と展開、暗号化と復号化、様々な文字エンコーディング間の | |
2035 | 変換を含むかも知れません。 | |
2036 | ||
2037 | =begin original | |
2038 | ||
2039 | Full discussion about the features of PerlIO is out of scope for this | |
2040 | tutorial, but here is how to recognize the layers being used: | |
2041 | ||
2042 | =end original | |
2043 | ||
2044 | PerlIO の機能に関する完全な議論はこのチュートリアルの対象外ですが、 | |
2045 | 層が使われていることをどうやって認識するかを以下に示します: | |
2046 | ||
2047 | =over 4 | |
2048 | ||
2049 | =item * | |
2050 | ||
2051 | =begin original | |
2052 | ||
2053 | The three-(or more)-argument form of C<open> is being used and the | |
2054 | second argument contains something else in addition to the usual | |
2055 | C<< '<' >>, C<< '>' >>, C<< '>>' >>, C<< '|' >> and their variants, | |
2056 | for example: | |
2057 | ||
2058 | =end original | |
2059 | ||
2060 | 3 (以上) 引数形式の C<open> が使われ、2 番目の引数に通常の | |
2061 | C<< '<' >>, C<< '>' >>, C<< '>>' >>, C<< '|' >> およびそのバリエーション | |
2062 | 以外の何かが含まれている場合; 例えば: | |
2063 | ||
2064 | open(my $fh, "<:crlf", $fn); | |
2065 | ||
2066 | =item * | |
2067 | ||
2068 | =begin original | |
2069 | ||
2070 | The two-argument form of C<binmode> is being used, for example | |
2071 | ||
2072 | =end original | |
2073 | ||
2074 | 2 引数形式の C<binmode> が使われている場合; 例えば | |
2075 | ||
2076 | binmode($fh, ":encoding(utf16)"); | |
2077 | ||
2078 | =back | |
2079 | ||
2080 | =begin original | |
2081 | ||
2082 | For more detailed discussion about PerlIO see L<PerlIO>; | |
2083 | for more detailed discussion about Unicode and I/O see L<perluniintro>. | |
2084 | ||
2085 | =end original | |
2086 | ||
2087 | PerlIO に関するより詳細な議論については L<PerlIO> を参照してください; | |
2088 | Unicode と I/O に関するより詳細な議論については L<perluniintro> を | |
2089 | 参照してください。 | |
2090 | ||
2091 | =head1 SEE ALSO | |
2092 | ||
2093 | =begin original | |
2094 | ||
2095 | The C<open> and C<sysopen> functions in perlfunc(1); | |
2096 | the system open(2), dup(2), fopen(3), and fdopen(3) manpages; | |
2097 | the POSIX documentation. | |
2098 | ||
2099 | =end original | |
2100 | ||
2101 | perlfunc(1) の C<open> 及び C<sysopen> 関数; | |
2102 | システムの open(2), dup(2), fopen(3), fdopen(3) の man ページ; | |
2103 | POSIX 文書。 | |
2104 | ||
867 | 2105 | =head1 AUTHOR and COPYRIGHT |
868 | 2106 | |
869 | Copyright | |
2107 | Copyright 1998 Tom Christiansen. | |
870 | 2108 | |
871 | This documentation is free; you can redistribute it and/or modify it | |
2109 | This documentation is free; you can redistribute it and/or modify it | |
872 | the same terms as Perl itself. | |
2110 | under the same terms as Perl itself. | |
873 | 2111 | |
2112 | Irrespective of its distribution, all code examples in these files are | |
2113 | hereby placed into the public domain. You are permitted and | |
2114 | encouraged to use this code in your own programs for fun or for profit | |
2115 | as you see fit. A simple comment in the code giving credit would be | |
2116 | courteous but is not required. | |
2117 | ||
2118 | =head1 HISTORY | |
2119 | ||
2120 | First release: Sat Jan 9 08:09:11 MST 1999 | |
2121 | ||
874 | 2122 | =begin meta |
875 | 2123 | |
876 | Translate: SHIRAKTA Kentaro <argrath@ub32.org> | |
2124 | Translate: SHIRAKATA Kentaro <argrath@ub32.org> | |
877 | Status: completed | |
878 | 2125 | |
879 | 2126 | =end meta |