perlopentut > 5.12.1 との差分

perlopentut 5.12.1 と 5.36.0 の差分

11
2=encoding euc-jp
2=encoding utf8
33
44=head1 NAME
55
66=begin original
77
8perlopentut - tutorial on opening things in Perl
8perlopentut - simple recipes for opening files and pipes in Perl
99
1010=end original
1111
12perlopentut - Perl でいろんなものを開ためのチュートリアル
12perlopentut - Perl でファイルを開りパイプを使ったりするための簡単なレシピ
1313
1414=head1 DESCRIPTION
1515
1616=begin original
1717
18Perl has two simple, built-in ways to open files: the shell way for
18Whenever you do I/O on a file in Perl, you do so through what in Perl is
19convenience, and the C way for precision. The shell way also has 2- and
19called a B<filehandle>. A filehandle is an internal name for an external
203-argument forms, which have different semantics for handling the filename.
20file. It is the job of the C<open> function to make the association
21The choice is yours.
21between the internal name and the external name, and it is the job
22of the C<close> function to break that association.
2223
2324=end original
2425
25Perl には、ファイルを開くための 2 つの単純な組み込みの手段があります:
26Perl ファイルに対して入出力するとき、Perl では B<ファイルハンドル> と
26利便性ためのシェル風の方法と、正確性のための C 風の方法です。
27呼ばれるもを通して行います。
27シェ風の方法に 2 引数と 3 引数があり、ファイル名の扱い関して
28ファイハンドル外部ファイルに対する内部名です。
28異なった動作します。
29C<open> 関数の仕事は内部名と外部名関連づけることで、C<close> 関数は
29選択はあなた次第です。
30関連づけを壊すことです。
30
31=head1 Open E<agrave> la shell
32
33(シェル風に開く)
34
35=begin original
36
37Perl's C<open> function was designed to mimic the way command-line
38redirection in the shell works. Here are some basic examples
39from the shell:
40
41=end original
42
43Perl の C<open> 関数は、シェルでのコマンドラインのリダイレクトをまねて
44設計されています。
45以下はシェルでの基本的な例です:
46
47 $ myprogram file1 file2 file3
48 $ myprogram < inputfile
49 $ myprogram > outputfile
50 $ myprogram >> outputfile
51 $ myprogram | otherprogram
52 $ otherprogram | myprogram
53
54=begin original
55
56And here are some more advanced examples:
57
58=end original
59
60そして以下はもう少し高度な例です:
61
62 $ otherprogram | myprogram f1 - f2
63 $ otherprogram 2>&1 | myprogram -
64 $ myprogram <&3
65 $ myprogram >&4
66
67=begin original
68
69Programmers accustomed to constructs like those above can take comfort
70in learning that Perl directly supports these familiar constructs using
71virtually the same syntax as the shell.
72
73=end original
74
75上述のような方法に慣れているプログラマにとっては、Perl がシェルと事実上
76同じ文法を使った親しんでいる構造に直接対応していることは
77学ぶのが容易になります。
78
79=head2 Simple Opens
80
81(単純に開く)
8231
8332=begin original
8433
85The C<open> function takes two arguments: the first is a filehandle,
34For your convenience, Perl sets up a few special filehandles that are
86and the second is a single string comprising both what to open and how
35already open when you run. These include C<STDIN>, C<STDOUT>, C<STDERR>,
87to open it. C<open> returns true when it works, and when it fails,
36and C<ARGV>. Since those are pre-opened, you can use them right away
88returns a false value and sets the special variable C<$!> to reflect
37without having to go to the trouble of opening them yourself:
89the system error. If the filehandle was previously opened, it will
90be implicitly closed first.
9138
9239=end original
9340
94C<open> 関数 2 つの引数を取ります: 1 つめはファイルハンドルで、
41便利なように、Perl実行開始時に既に開いているいく特別な
952 つめは何開くかとどう開くかで構成される単一の文字列です。
42ファイルハンドル設定します。
96C<open> は成功すると真を返し、失敗すると偽を返して特殊変数 C<$!>
43それは C<STDIN>, C<STDOUT>, C<STDERR>, C<ARGV> です。
97システムエラー反映します。
44これらは既に開いているので、自分でこれら開くときの問題を受けることなく
98指定されたファイルハンドル以前に開かれていた場合は、暗黙の内に
45正しく使うことできます。
99まず閉じられます。
10046
101=begin original
47 print STDERR "This is a debugging message.\n";
10248
103For example:
49 print STDOUT "Please enter something: ";
50 $response = <STDIN> // die "how come no input?";
51 print STDOUT "Thank you!\n";
10452
105=end original
53 while (<ARGV>) { ... }
106
107例えば:
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: $!");
11354
11455=begin original
11556
116If you prefer the low-punctuation version, you could write that this way:
57As you see from those examples, C<STDOUT> and C<STDERR> are output
58handles, and C<STDIN> and C<ARGV> are input handles. They are
59in all capital letters because they are reserved to Perl, much
60like the C<@ARGV> array and the C<%ENV> hash are. Their external
61associations were set up by your shell.
11762
11863=end original
11964
120句読点が少ない方が好みな、以下のようにも書けます:
65これらの例で見られるように、C<STDOUT> と C<STDERR> は出力ハンドルで、
66C<STDIN> と C<ARGV> は入力ハンドルです。
122 open INFO, "< datafile" or die "can't open datafile: $!";
67これらは C<@ARGV> 配列や C<%ENV> ハッシュと同様に Perl によって
123 open RESULTS,"> runstats" or die "can't open runstats: $!";
68予約されているので、全て大文字になっています。
124 open LOG, ">> logfile " or die "can't open logfile: $!";
69これらの外部関連づけはシェルによって行われます。
12570
12671=begin original
12772
128A few things to notice. First, the leading less-than is optional.
73You will need to open every other filehandle on your own. Although there
129If omitted, Perl assumes that you want to open the file for reading.
74are many variants, the most common way to call Perl's open() function
75is with three arguments and one return value:
13076
13177=end original
13278
133つか気がつくことがあります。
79その他のファイルハンドルは自分で開必要があります。
134先頭「大り」省略可能です。
80多くのバリエーションはありすがPerl open() 関数を開く最も一般的方法
135省略されると、Perl はファイルを読み込みのために開きたい仮定しま
813 引数一つの返り値のもので:
13682
13783=begin original
13884
139Note also that the first example uses the C<||> logical operator, and the
85C< I<OK> = open(I<HANDLE>, I<MODE>, I<PATHNAME>)>
140second uses C<or>, which has lower precedence. Using C<||> in the latter
141examples would effectively mean
14286
14387=end original
14488
145最初の例は C<||> 論理演算子を使っていて、二つめの例はより優先順位の低い
89C< I<OK> = open(I<HANDLE>, I<MODE>, I<PATHNAME>)>
146C<or> を使っていることにも注意してください。
147後者の例で C<||> を使うと、実際には以下のような意味になり
148
149 open INFO, ( "< datafile" || die "can't open datafile: $!" );
15090
15191=begin original
15292
153which is definitely not what you want.
93Where:
15494
15595=end original
15696
157あなたが望んでいるのと全く違うとになります。
97こで:
158
159=begin original
160
161The other important thing to notice is that, just as in the shell,
162any whitespace before or after the filename is ignored. This is good,
163because you wouldn't want these to do different things:
164
165=end original
16698
167他の注意するべき重要なこととしては、シェルと同様、ファイル名の前後の
99=over
168空白は無視されることです。
169これはよいことです; なぜなら、以下のものが違うことをすることは
170望まないだろうからです:
171100
172 open INFO, "<datafile"
101=item I<OK>
173 open INFO, "< datafile"
174 open INFO, "< datafile"
175102
176103=begin original
177104
178Ignoring surrounding whitespace also helps for when you read a filename
105will be some defined value if the open succeeds, but
179in from a different file, and forget to trim it before opening:
106C<undef> if it fails;
180107
181108=end original
182109
183周りの空白を無視するは、ファイル名を別ファイルか読み込んで
110は、開くに成功すれば何かの定義された値失敗すれば C<undef> です;
184開く前に空白を取り除くのを忘れたときにも助けになります:
185111
186 $filename = <INFO>; # oops, \n still there
112=item I<HANDLE>
187 open(EXTRA, "< $filename") || die "can't open $filename: $!";
188113
189114=begin original
190115
191This is not a bug, but a feature. Because C<open> mimics the shell in
116should be an undefined scalar variable to be filled in by the
192its style of using redirection arrows to specify how to open the file, it
117C<open> function if it succeeds;
193also does so with respect to extra whitespace around the filename itself
194as well. For accessing files with naughty names, see
195L<"Dispelling the Dweomer">.
196118
197119=end original
198120
199これはバグではありません仕様です
121これは、成功すれば C<open> 関数によって埋められる未定義のスカラ変数です;
200C<open> はどのようにファイルを開くかを指定するのにリダイレクトの矢印を
201使うことでシェルを真似ているので、ファイル名の周りの空白についても
202同じように扱います。
203行儀の悪い名前のファイルにアクセスするためには、
204L<"Dispelling the Dweomer"> を参照してください。
205
206=begin original
207122
208There is also a 3-argument version of C<open>, which lets you put the
123=item I<MODE>
209special 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: $!";
217124
218125=begin original
219126
220In this case, the filename to open is the actual string in C<$datafile>,
127is the access mode and the encoding format to open the file with;
221so you don't have to worry about C<$datafile> containing characters
222that might influence the open mode, or whitespace at the beginning of
223the filename that would be absorbed in the 2-argument version. Also,
224any reduction of unnecessary string interpolation is a good thing.
225128
226129=end original
227130
228の場合、開くファイル名は C<$datafile> 実際の文字列なの
131れはファイルを開くときアクセスモードとエンコーディング型式す;
229C<$datafile> に開くモードに影響を与える文字や、
2302 引数版では吸収されるファイル名の先頭の空白が含まれているかどうかを
231心配する必要はありません。
232また、不必要な文字列変換が削減されるのもよいことです。
233132
234=head2 Indirect Filehandles
133=item I<PATHNAME>
235
236(間接ファイルハンドル)
237134
238135=begin original
239136
240C<open>'s first argument can be a reference to a filehandle. As of
137is the external name of the file you want opened.
241perl 5.6.0, if the argument is uninitialized, Perl will automatically
242create a filehandle and put a reference to it in the first argument,
243like so:
244138
245139=end original
246140
247C<open> の最初の引数ファイルハンドルへリファレンスにすることも出来ます。
141これ開きたいファイルの外部名です。
248perl 5.6.0 以降、引数が初期化されていない場合、Perl は
249以下のように、自動的にファイルハンドルを作成して、それへのリファレンスを
250最初の引数に設定します:
251142
252 open( my $in, $infile ) or die "Couldn't read $infile: $!";
143=back
253 while ( <$in> ) {
254 # do something with $_
255 }
256 close $in;
257144
258145=begin original
259146
260Indirect filehandles make namespace management easier. Since filehandles
147Most of the complexity of the C<open> function lies in the many
261are global to the current package, two subroutines trying to open
148possible values that the I<MODE> parameter can take on.
262C<INFILE> will clash. With two functions opening indirect filehandles
263like C<my $infile>, there's no clash and no need to worry about future
264conflicts.
265149
266150=end original
267151
268間接ファイルハンドルは、名前空間管理より容易にします。
152C<open> 関数の複雑さの大部分は、I<MODE> 引数が多くの値
269ファイルハンドルは現在パッケージに対してグローバルなの
153取ることのできることにあります。
270二つのサブルーチンが C<INFILE> を開こうとすると衝突します。
271二つの関数が C<my $infil> のように間接ファイルハンドルで開いていると、
272衝突は発生せず、将来の衝突を気にする必要もありません。
273154
274155=begin original
275156
276Another convenient behavior is that an indirect filehandle automatically
157One last thing before we show you how to open files: opening
277closes when it goes out of scope or when you undefine it:
158files does not (usually) automatically lock them in Perl. See
159L<perlfaq5> for how to lock.
278160
279161=end original
280162
281もう一つ便利は振舞いとして、間接ファイルハンドルは、スコープ外に出るか
163ファイル開き方を説明す前に最後に一言: Perl ではファイルを開いても
282undef にされると、自動的に閉じま:
164(普通は)自動的にロックることはしません。
165ロックの方法については L<perlfaq5> を参照してください。
284 sub firstline {
285 open( my $in, shift ) && return scalar <$in>;
286 # no close() required
287 }
288
289=head2 Pipe Opens
290166
291(パイプを開く)
167=head1 Opening Text Files
292
293=begin original
294168
295In C, when you want to open a file using the standard I/O library,
169(テキストファイルを開く)
296you use the C<fopen> function, but when opening a pipe, you use the
297C<popen> function. But in the shell, you just use a different redirection
298character. That's also the case for Perl. The C<open> call
299remains the same--just its argument differs.
300170
301=end original
171=head2 Opening Text Files for Reading
302172
303C では、標準 I/O ライブラリを使ってファイルを開きたいときは C<fopen> を
173(読み込み用にテキストファイルを開く)
304使いますが、パイプを開くときには C<popen> 関数を使います。
305しかし、シェルでは、単に違うリダイレクト文字を使います。
306これは Perl の場合にも当てはまります。
307C<open> 呼び出しは同じままです -- 単にその引数が変わります。
308174
309175=begin original
310176
311If the leading character is a pipe symbol, C<open> starts up a new
177If you want to read from a text file, first open it in
312command and opens a write-only filehandle leading into that command.
178read-only mode like this:
313This lets you write into that handle and have what you write show up on
314that command's standard input. For example:
315179
316180=end original
317181
318先頭の文字がパプ記号の場合、C<open> は新しいコマンを準備して、
182テキストファルを読み込みたい場合、まず次のように読み込み専用モー
319そのコマンドへと導かれる書き込み専用のファイルハンドルを開きます
183開きます:
320これによって、あなたがこのハンドルに書き込んだものがコマンドの
321標準入力に渡されるようになります。
322例えば:
323184
324 open(PRINTER, "| lpr -Plp1") || die "can't run lpr: $!";
185 my $filename = "/some/path/to/a/textfile/goes/here";
325 print PRINTER "stuff\n";
186 my $encoding = ":encoding(UTF-8)";
326 close(PRINTER) || die "can't close lpr: $!";
187 my $handle = undef; # this will be filled in on success
327188
328=begin original
189 open($handle, "< $encoding", $filename)
190 || die "$0: can't open $filename for reading: $!";
330If the trailing character is a pipe, you start up a new command and open a
331read-only filehandle leading out of that command. This lets whatever that
332command writes to its standard output show up on your handle for reading.
333For example:
334
335=end original
336
337末尾の文字がパイプの場合、新しいコマンドを準備して、
338そのコマンドから導かれる読み込み専用のファイルハンドルを開きます。
339これにより、そのコマンドが標準出力にしたものはなんでも読み込み用の
340ファイルハンドルに現れます。
341例えば:
342
343 open(NET, "netstat -i -n |") || die "can't fork netstat: $!";
344 while (<NET>) { } # do something with input
345 close(NET) || die "can't close netstat: $!";
346191
347192=begin original
348193
349What happens if you try to open a pipe to or from a non-existent
194As with the shell, in Perl the C<< "<" >> is used to open the file in
350command? If possible, Perl will detect the failure and set C<$!> as
195read-only mode. If it succeeds, Perl allocates a brand new filehandle for
351usual. But if the command contains special shell characters, such as
196you and fills in your previously undefined C<$handle> argument with a
352C<E<gt>> or C<*>, called 'metacharacters', Perl does not execute the
197reference to that handle.
353command directly. Instead, Perl runs the shell, which then tries to
354run the command. This means that it's the shell that gets the error
355indication. In such a case, the C<open> call will only indicate
356failure if Perl can't even run the shell. See L<perlfaq8/"How can I
357capture STDERR from an external command?"> to see how to cope with
358this. There's also an explanation in L<perlipc>.
359198
360199=end original
361200
362存在しないコマンド対してパ開こうとすると何が起こるしょうか?
201シェルと同様、Perl でもファ読み込み専用モード開くために
363可能なら、Perl は失敗を検出していつも通り C<$!> をセットします。
202C<< "<" >> が使われます。
364しかしコマンドに「メタ文字」と呼ばれる C<E<gt>> や C<*> のような
203これに成功するとPerl は新いファイルハンドルを割り当て、未定義だった
365特殊シェル文字が含まれていると、Perl はコマンドを直接実行しません
204C<$handle> 引数にそのハンドルへのリファレンス設定しま
366その代わりに、Perl はシェルを実行し、それからコマンドを
367実行しようとします。
368これは、エラーを受け取るのはシェルであることを意味します。
369このような場合、C<open> 呼び出しは、たとえ Perl がシェルを実行できなかった
370場合でも、失敗を示すだけです。
371これを扱う方法については、
372L<perlfaq8/"How can I capture STDERR from an external command?"> を
373参照してください。
374L<perlipc> にも説明があります。
375205
376206=begin original
377207
378If you would like to open a bidirectional pipe, the IPC::Open2
208Now you may use functions like C<readline>, C<read>, C<getc>, and
379library will handle this for you. Check out
209C<sysread> on that handle. Probably the most common input function
380L<perlipc/"Bidirectional Communication with Another Process">
210is the one that looks like an operator:
381211
382212=end original
383213
384双方向パイプを開きたい場合は、IPC::Open2 ライブラリが使えます。
214これでこのハンドルに対して C<readline>, C<read>, C<getc>,
385L<perlipc/"Bidirectional Communication with Another Process">
215C<sysread> のような関数が使えます。
386参照してださい。
216おそら最も一般的な入力関数は演算子のように見えるものでしょう:
387217
388=begin original
218 $line = readline($handle);
219 $line = <$handle>; # same thing
390perl-5.6.x introduced a version of piped open that executes a process
391based on its command line arguments without relying on the shell. (Similar
392to the C<system(@LIST)> notation.) This is safer and faster than executing
393a single argument pipe-command, but does not allow special shell
394constructs. (It is also not supported on Microsoft Windows, Mac OS Classic
395or RISC OS.)
396
397=end original
398
399perl-5.6.x から、シェルに頼らずにコマンドライン引数を基にしてプロセスを
400実行するパイプオープンが導入されました。
401(C<system(@LIST)> 記法と同様です。)
402これは 1 引数のパイプコマンドを実行するより安全で高速ですが、特殊シェル
403構文は使えません。
404(また、Microsoft Windows, Mac OS Classic, RISC OS でも対応していません。)
405220
406221=begin original
407222
408Here's an example of C<open '-|'>, which prints a random Unix
223Because the C<readline> function returns C<undef> at end of file or
409fortune cookie as uppercase:
224upon error, you will sometimes see it used this way:
410225
411226=end original
412227
413以下は C<open '-|'> の例で、ンダムな Unix おみくじ大文字で表示しま:
228C<readline> 関数はファイル終端やエーのときに C<undef>ので、
229時々次のように使われているのを見るでしょう:
414230
415 my $collection = shift(@ARGV);
231 $line = <$handle>;
416 open my $fortune, '-|', 'fortune', $collection
232 if (defined $line) {
417 or die "Could not find fortune - $!";
233 # do something with $line
418 while (<$fortune>)
234 }
419 {
235 else {
420 print uc($_);
236 # $line is not valid, so skip it
421237 }
422 close($fortune);
423
424=begin original
425
426And this C<open '|-'> pipes into lpr:
427
428=end original
429
430そしてこれは C<open '|-'> パイプを lpr に送ります:
431
432 open my $printer, '|-', 'lpr', '-Plp1'
433 or die "can't run lpr: $!";
434 print {$printer} "stuff\n";
435 close($printer)
436 or die "can't close lpr: $!";
437
438=head2 The Minus File
439
440("-" ファイル)
441
442=begin original
443
444Again following the lead of the standard shell utilities, Perl's
445C<open> function treats a file whose name is a single minus, "-", in a
446special way. If you open minus for reading, it really means to access
447the standard input. If you open minus for writing, it really means to
448access the standard output.
449
450=end original
451
452再び標準シェルの機能に合わせるように、Perl の
453C<open> 関数は、名前がマイナス一つ "-" だけのファイルを特別に扱います。
454読み込み用にマイナスを開くと、実際には標準入力にアクセスします。
455書き込み用にマイナスを開くと、実際には標準出力にアクセスします。
456
457=begin original
458
459If minus can be used as the default input or default output, what happens
460if you open a pipe into or out of minus? What's the default command it
461would run? The same script as you're currently running! This is actually
462a stealth C<fork> hidden inside an C<open> call. See
463L<perlipc/"Safe Pipe Opens"> for details.
464
465=end original
466
467マイナスがデフォルトの入力やデフォルトの出力として使えるとすると、
468パイプに対してマイナスを使うとどうなるでしょう?
469デフォルトのコマンドとして何が実行されるのでしょう?
470今実行している同じスクリプトです!
471これは実際には C<open> 呼び出し内で隠れた C<fork> が行われます。
472詳しくは L<perlipc/"Safe Pipe Opens"> を参照してください。
473
474=head2 Mixing Reads and Writes
475
476(読み書きを混ぜる)
477
478=begin original
479
480It is possible to specify both read and write access. All you do is
481add a "+" symbol in front of the redirection. But as in the shell,
482using a less-than on a file never creates a new file; it only opens an
483existing one. On the other hand, using a greater-than always clobbers
484(truncates to zero length) an existing file, or creates a brand-new one
485if there isn't an old one. Adding a "+" for read-write doesn't affect
486whether it only works on existing files or always clobbers existing ones.
487
488=end original
489
490読み書きアクセス双方を指定することは可能です。
491必要なことはリダイレクトの前に "+" の文字を加えるだけです。
492しかしシェルの場合と同様、ファイルに小なり記号を使っても新しいファイルが
493作成されることはありません; すでにあるファイルを開くだけです。
494一方、大なり記号を使うと、ファイルがある場合には常に上書き
495(長さ 0 に切り詰め)られ、ファイルがない場合は新しいファイルが作成されます。
496読み書き用に "+" を追加しても、既にあるファイルにだけ動作するか
497既にあるファイルを上書きするかということには影響を与えません。
498
499 open(WTMP, "+< /usr/adm/wtmp")
500 || die "can't open /usr/adm/wtmp: $!";
501
502 open(SCREEN, "+> lkscreen")
503 || die "can't open lkscreen: $!";
504
505 open(LOGFILE, "+>> /var/log/applog")
506 || die "can't open /var/log/applog: $!";
507
508=begin original
509
510The first one won't create a new file, and the second one will always
511clobber an old one. The third one will create a new file if necessary
512and not clobber an old one, and it will allow you to read at any point
513in the file, but all writes will always go to the end. In short,
514the first case is substantially more common than the second and third
515cases, which are almost always wrong. (If you know C, the plus in
516Perl's C<open> is historically derived from the one in C's fopen(3S),
517which it ultimately calls.)
518
519=end original
520
521一つ目のものは新しいファイルを作ることはなく、二つ目のものは常に古い
522ファイルを上書きします。
523三つ目のものは必要があれば新しいファイルを作りますが、古いファイルを
524上書きせず、ファイルのどの地点でも読み込むことができますが、
525書き込みは常に末尾に行われます。
526要するに、一つ目のものは(ほとんど常に間違っている)二つ目や三つ目の
527ものよりもかなり一般的です。
528(もし C を知っているなら、Perl の C<open> で使われるプラス記号が
529歴史的には (最終的に呼ばれることになる) C の fopen(3S) に由来しています。)
530
531=begin original
532
533In fact, when it comes to updating a file, unless you're working on
534a binary file as in the WTMP case above, you probably don't want to
535use this approach for updating. Instead, Perl's B<-i> flag comes to
536the rescue. The following command takes all the C, C++, or yacc source
537or header files and changes all their foo's to bar's, leaving
538the old version in the original filename with a ".orig" tacked
539on the end:
540
541=end original
542
543実際、ファイルを更新するとき、上述の WTMP の場合のようなバイナリファイルに
544対して作業をするのでない限り、おそらく更新のためにこの手法を
545使いたくないでしょう。
546代わりに、Perl の B<-i> フラグが助けになります。
547以下のコマンドは C, C++, yacc 全てののソースファイルとヘッダファイルを
548取って、その中の全ての foo を bar に変更し、原版は元のファイル名の末尾に
549".orig" を付けたファイルに保持します:
550
551 $ perl -i.orig -pe 's/\bfoo\b/bar/g' *.[Cchy]
552
553=begin original
554
555This is a short cut for some renaming games that are really
556the best way to update textfiles. See the second question in
557L<perlfaq5> for more details.
558
559=end original
560
561これは実際にはテキストファイルを更新するための最良の方法であるリネーム
562手法へのショートカットです。
563さらなる詳細については L<perlfaq5> の 2 番目の質問を参照してください。
564
565=head2 Filters
566
567(フィルタ)
568
569=begin original
570
571One of the most common uses for C<open> is one you never
572even notice. When you process the ARGV filehandle using
573C<< <ARGV> >>, Perl actually does an implicit open
574on each file in @ARGV. Thus a program called like this:
575
576=end original
577
578C<open> のもっとも一般的な使い方の一つは、使っていることを
579気づきすらしないものです。
580ARGV ファイルハンドルを C<< <ARGV> >> を使って処理するとき、Perl は
581実際は @ARGV の各ファイルを暗黙の内に開いています。
582従って、以下のようなプログラムは:
583
584 $ myprogram file1 file2 file3
585
586=begin original
587
588can have all its files opened and processed one at a time
589using a construct no more complex than:
590
591=end original
592
593以下のようなものより複雑な構文を使わなくても、それぞれのファイルを
594開いて一度に処理できます:
595
596 while (<>) {
597 # do something with $_
598 }
599
600=begin original
601
602If @ARGV is empty when the loop first begins, Perl pretends you've opened
603up minus, that is, the standard input. In fact, $ARGV, the currently
604open file during C<< <ARGV> >> processing, is even set to "-"
605in these circumstances.
606
607=end original
608
609ループが最初に開始したときに @ARGV が空なら、Perl はマイナス記号
610(つまり標準入力) を開いたかのように振る舞います。
611実際、C<< <ARGV> >> で現在開いているファイルを示す $ARGV には、
612この慣習によって "-" がセットされます。
613
614=begin original
615
616You are welcome to pre-process your @ARGV before starting the loop to
617make sure it's to your liking. One reason to do this might be to remove
618command options beginning with a minus. While you can always roll the
619simple ones by hand, the Getopts modules are good for this:
620
621=end original
622
623好みの形にするために、ループの開始前に @ARGV を前処理しても問題ありません。
624こうするための理由の一つは、マイナスから始まるコマンドオプションを
625削除するためです。
626いつでも自分で単純なものを作ることができる一方、
627Getopts モジュールはこれを行うのによいものです:
628
629 use Getopt::Std;
630
631 # -v, -D, -o ARG, sets $opt_v, $opt_D, $opt_o
632 getopts("vDo:");
633
634 # -v, -D, -o ARG, sets $args{v}, $args{D}, $args{o}
635 getopts("vDo:", \%args);
636
637=begin original
638
639Or the standard Getopt::Long module to permit named arguments:
640
641=end original
642
643あるいは、名前付きの引数を使えるようにするための
644標準の Getopt::Long モジュールもあります:
645
646 use Getopt::Long;
647 GetOptions( "verbose" => \$verbose, # --verbose
648 "Debug" => \$debug, # --Debug
649 "output=s" => \$output );
650 # --output=somestring or --output somestring
651
652=begin original
653
654Another reason for preprocessing arguments is to make an empty
655argument list default to all files:
656
657=end original
658
659引数を前処理するためのもう一つの理由は、空引数リストの時は
660デフォルトで全てのファイルとする場合です:
661
662 @ARGV = glob("*") unless @ARGV;
663
664=begin original
665
666You could even filter out all but plain, text files. This is a bit
667silent, of course, and you might prefer to mention them on the way.
668
669=end original
670
671プレーンなテキストファイル以外をフィルタリングすることもできます。
672これはもちろん少し静かなので、途中でそれに言及したいかもしれません。
673
674 @ARGV = grep { -f && -T } @ARGV;
675
676=begin original
677
678If you're using the B<-n> or B<-p> command-line options, you
679should put changes to @ARGV in a C<BEGIN{}> block.
680
681=end original
682
683もし B<-n> や B<-p> のコマンドラインオプションを使っているなら、
684@ARGV への変更は C<BEGIN{}> ブロックで行うべきです。
685
686=begin original
687
688Remember that a normal C<open> has special properties, in that it might
689call fopen(3S) or it might called popen(3S), depending on what its
690argument looks like; that's why it's sometimes called "magic open".
691Here's an example:
692
693=end original
694
695通常の C<open> は特別な特性を持っていて、引数が何に見えるかによって、
696fopen(3S) を呼ぶかもしれませんし、popen(3S) を呼ぶかもしれません;
697これが時々「マジカルに開く」と呼ばれる理由です。
698以下は例です:
699
700 $pwdinfo = `domainname` =~ /^(\(none\))?$/
701 ? '< /etc/passwd'
702 : 'ypcat passwd |';
703
704 open(PWD, $pwdinfo)
705 or die "can't open $pwdinfo: $!";
706
707=begin original
708
709This sort of thing also comes into play in filter processing. Because
710C<< <ARGV> >> processing employs the normal, shell-style Perl C<open>,
711it respects all the special things we've already seen:
712
713=end original
714
715このようなことはフィルタ処理でも起こります。
716C<< <ARGV> >> 処理は通常のシェル風の Perl C<open> を用いるので、
717今までに見てきた全ての特別なことが反映されます:
718
719 $ myprogram f1 "cmd1|" - f2 "cmd2|" f3 < tmpfile
720
721=begin original
722
723That program will read from the file F<f1>, the process F<cmd1>, standard
724input (F<tmpfile> in this case), the F<f2> file, the F<cmd2> command,
725and finally the F<f3> file.
726
727=end original
728
729このプログラムはファイル F<f1>、プロセス F<cmd1>、標準入力
730(この場合は F<tmpfile>)、ファイル F<f2>、コマンド F<cmd2>、
731ファイル F<f3> から読み込みます。
732
733=begin original
734
735Yes, this also means that if you have files named "-" (and so on) in
736your directory, they won't be processed as literal files by C<open>.
737You'll need to pass them as "./-", much as you would for the I<rm> program,
738or you could use C<sysopen> as described below.
739
740=end original
741
742はい、これは、"-" (あるいは同じような) 名前を持つファイルがある場合、
743C<open> によってそのまま処理することができないことも意味します。
744I<rm> プログラムに対して行うのと同様に "./-" という形で渡すか、後述する
745C<sysopen> を使う必要があります。
746
747=begin original
748
749One of the more interesting applications is to change files of a certain
750name into pipes. For example, to autoprocess gzipped or compressed
751files by decompressing them with I<gzip>:
752
753=end original
754
755もっと興味深いアプリケーションの一つは、ある名前を持ったファイルを
756パイプに変更するものです。
757例えば、gzip や compress されたファイルを、I<gzip> を使って自動的に
758展開するには:
759
760 @ARGV = map { /\.(gz|Z)$/ ? "gzip -dc $_ |" : $_ } @ARGV;
761
762=begin original
763
764Or, if you have the I<GET> program installed from LWP,
765you can fetch URLs before processing them:
766
767=end original
768
769あるいは、LWP からインストールされる I<GET> プログラムがあるなら、
770処理する前に URL をフェッチできます:
771
772 @ARGV = map { m#^\w+://# ? "GET $_ |" : $_ } @ARGV;
773
774=begin original
775
776It's not for nothing that this is called magic C<< <ARGV> >>.
777Pretty nifty, eh?
778
779=end original
780
781これがマジカルな C<< <ARGV> >> と呼ばれるのは理由のないことではありません。
782かなりしゃれてるでしょ?
783
784=head1 Open E<agrave> la C
785
786(C 風に開く)
787
788=begin original
789
790If you want the convenience of the shell, then Perl's C<open> is
791definitely the way to go. On the other hand, if you want finer precision
792than C's simplistic fopen(3S) provides you should look to Perl's
793C<sysopen>, which is a direct hook into the open(2) system call.
794That does mean it's a bit more involved, but that's the price of
795precision.
796
797=end original
798
799シェルの便利さを求めているなら、Perl の C<open> はまさにぴったりです。
800一方、C の単純な fopen(3S) が提供しているものより高い精度を求めているなら、
801open(2) システムコールへの直接的なフックである、Perl の
802C<sysopen> を見るべきです。
803これはもう少し深く関わることを意味しますが、これは精度のコストです。
804
805=begin original
806
807C<sysopen> takes 3 (or 4) arguments.
808
809=end original
810
811C<sysopen> は 3 (または 4) 引数を取ります。
812
813 sysopen HANDLE, PATH, FLAGS, [MASK]
814
815=begin original
816
817The HANDLE argument is a filehandle just as with C<open>. The PATH is
818a literal path, one that doesn't pay attention to any greater-thans or
819less-thans or pipes or minuses, nor ignore whitespace. If it's there,
820it's part of the path. The FLAGS argument contains one or more values
821derived from the Fcntl module that have been or'd together using the
822bitwise "|" operator. The final argument, the MASK, is optional; if
823present, it is combined with the user's current umask for the creation
824mode of the file. You should usually omit this.
825
826=end original
827
828HANDLE 引数は C<open> と同様のファイルハンドルです。
829PATH はリテラルなパスで、大なりや小なりやパイプやマイナスや空白の
830無視といったことに一切注意を払いません。
831もしこれらの文字があれば、それはパスの一部です。
832FLAGS 引数は、ビット単位 "|" 演算子で結合できる、Fcntl モジュールに
833由来する一つ以上の値を指定します。
834最後の引数である MASK はオプションです; もしあれば、これは
835ファイルの作成モードのためのユーザーの現在の umask と組み合わされます。
836普通はこれは省略するべきです。
837
838=begin original
839
840Although the traditional values of read-only, write-only, and read-write
841are 0, 1, and 2 respectively, this is known not to hold true on some
842systems. Instead, it's best to load in the appropriate constants first
843from the Fcntl module, which supplies the following standard flags:
844
845=end original
846
847読み込み専用、書き込み専用、読み書きを示す伝統的な値は
848それぞれ 0, 1, 2 ですが、これが正しくないシステムもあることが
849知られています。
850代わりに、以下の標準フラグを提供している Fcntl モジュールから
851最初に適切な定数を読み込むのが最善です:
852
853 O_RDONLY Read only
854 O_WRONLY Write only
855 O_RDWR Read and write
856 O_CREAT Create the file if it doesn't exist
857 O_EXCL Fail if the file already exists
858 O_APPEND Append to the file
859 O_TRUNC Truncate the file
860 O_NONBLOCK Non-blocking access
861
862=begin original
863
864Less common flags that are sometimes available on some operating
865systems include C<O_BINARY>, C<O_TEXT>, C<O_SHLOCK>, C<O_EXLOCK>,
866C<O_DEFER>, C<O_SYNC>, C<O_ASYNC>, C<O_DSYNC>, C<O_RSYNC>,
867C<O_NOCTTY>, C<O_NDELAY> and C<O_LARGEFILE>. Consult your open(2)
868manpage or its local equivalent for details. (Note: starting from
869Perl release 5.6 the C<O_LARGEFILE> flag, if available, is automatically
870added to the sysopen() flags because large files are the default.)
871
872=end original
873
874オペレーティングシステムによっては、
875 C<O_BINARY>, C<O_TEXT>, C<O_SHLOCK>, C<O_EXLOCK>,
876C<O_DEFER>, C<O_SYNC>, C<O_ASYNC>, C<O_DSYNC>, C<O_RSYNC>,
877C<O_NOCTTY>, C<O_NDELAY>, C<O_LARGEFILE> のような、それほど有名ではない
878フラグも利用可能です。
879詳しくは open(2) man ページその等価物を参照してください。
880(注意: Perl リリース 5.6 から、もし利用可能なら、sysopen() のフラグに
881自動的に C<O_LARGEFILE> フラグが付きます; 大きなファイルがデフォルトに
882なったからです。)
883
884=begin original
885
886Here's how to use C<sysopen> to emulate the simple C<open> calls we had
887before. We'll omit the C<|| die $!> checks for clarity, but make sure
888you always check the return values in real code. These aren't quite
889the same, since C<open> will trim leading and trailing whitespace,
890but you'll get the idea.
891
892=end original
893
894これは、前述した単純な C<open> をエミュレートするために C<sysopen> を
895使う方法です。
896明確化のために C<|| die $!> のチェックは省略しましたが、実際のコードでは
897常に返り値をチェックするようにしてください。
898C<open> は前後の空白を削除するのでこれは全く同じというわけではありませんが、
899想像はできるでしょう。
900
901=begin original
902
903To open a file for reading:
904
905=end original
906
907ファイルを読み込み用に開くには:
908
909 open(FH, "< $path");
910 sysopen(FH, $path, O_RDONLY);
911
912=begin original
913
914To open a file for writing, creating a new file if needed or else truncating
915an old file:
916
917=end original
918
919ファイルを書き込み用に開いて、必要なら新しいファイルを作り、そうでなければ
920古いファイルを切り詰めるには:
921
922 open(FH, "> $path");
923 sysopen(FH, $path, O_WRONLY | O_TRUNC | O_CREAT);
924
925=begin original
926
927To open a file for appending, creating one if necessary:
928
929=end original
930
931ファイルを追加用に開いて、もし必要なら新しいファイルを作るには:
932
933 open(FH, ">> $path");
934 sysopen(FH, $path, O_WRONLY | O_APPEND | O_CREAT);
935
936=begin original
937
938To open a file for update, where the file must already exist:
939
940=end original
941
942既に存在しているファイルを更新用に開くには:
943
944 open(FH, "+< $path");
945 sysopen(FH, $path, O_RDWR);
946
947=begin original
948
949And here are things you can do with C<sysopen> that you cannot do with
950a regular C<open>. As you'll see, it's just a matter of controlling the
951flags in the third argument.
952
953=end original
954
955そしてここでは普通の C<open> では出来ないことを C<sysopen> でしています。
956見てきたように、これは単に 3 番目の引数のフラグの制御の問題です。
957
958=begin original
959
960To open a file for writing, creating a new file which must not previously
961exist:
962
963=end original
964
965既に存在していたりはしない新しいファイルを作成して、ファイルを書き込み用に
966開くには:
967
968 sysopen(FH, $path, O_WRONLY | O_EXCL | O_CREAT);
969
970=begin original
971
972To open a file for appending, where that file must already exist:
973
974=end original
975
976既に存在している必要があるファイルを追加用に開くには:
977
978 sysopen(FH, $path, O_WRONLY | O_APPEND);
979
980=begin original
981
982To open a file for update, creating a new file if necessary:
983
984=end original
985
986必要なら新しいファイルを作成して、ファイルを更新用に開くには:
987
988 sysopen(FH, $path, O_RDWR | O_CREAT);
989
990=begin original
991
992To open a file for update, where that file must not already exist:
993
994=end original
995
996予め存在していてはならないファイルを交信用に開くには:
997
998 sysopen(FH, $path, O_RDWR | O_EXCL | O_CREAT);
999
1000=begin original
1001
1002To open a file without blocking, creating one if necessary:
1003
1004=end original
1005
1006必要ならファイルを作成して、ファイルをブロックせずに開くには:
1007
1008 sysopen(FH, $path, O_WRONLY | O_NONBLOCK | O_CREAT);
1009
1010=head2 Permissions E<agrave> la mode
1011
1012(権限モード)
1013
1014=begin original
1015
1016If you omit the MASK argument to C<sysopen>, Perl uses the octal value
10170666. The normal MASK to use for executables and directories should
1018be 0777, and for anything else, 0666.
1019
1020=end original
1021
1022C<sysopen> の MASK 引数を省略すると、Perl は 8 進数の 0666 を使います。
1023実行ファイルとディレクトリに対する通常の MASK は 0777で、それ以外の
1024ファイルでは 0666 です。
1025
1026=begin original
1027
1028Why so permissive? Well, it isn't really. The MASK will be modified
1029by your process's current C<umask>. A umask is a number representing
1030I<disabled> permissions bits; that is, bits that will not be turned on
1031in the created file's permissions field.
1032
1033=end original
1034
1035なぜそんなに権限を与えるのでしょう?
1036えっと、実際にはそうではありません。
1037MASK はプロセスの現在の C<umask> で修正されます。
1038umask は I<無効にする> 許可ビットを表現する数値です; つまり、
1039作成したファイルの許可フィールドを有効にすることはないということです。
1040
1041=begin original
1042
1043For example, if your C<umask> were 027, then the 020 part would
1044disable the group from writing, and the 007 part would disable others
1045from reading, writing, or executing. Under these conditions, passing
1046C<sysopen> 0666 would create a file with mode 0640, since C<0666 & ~027>
1047is 0640.
1048
1049=end original
1050
1051例えば、C<umask> が 027 の場合、020 の部分はグループによる書き込みと
1052実行を無効にし、007 の部分は他のユーザーによる読み込み、書き込み、
1053実行を無効にします。
1054この条件では、C<sysopen> に 0666 を渡すとモード 0640 でファイルを作ります;
1055C<0666 & ~027> は 0640 だからです。
1056
1057=begin original
1058
1059You should seldom use the MASK argument to C<sysopen()>. That takes
1060away the user's freedom to choose what permission new files will have.
1061Denying choice is almost always a bad thing. One exception would be for
1062cases where sensitive or private data is being stored, such as with mail
1063folders, cookie files, and internal temporary files.
1064
1065=end original
1066
1067C<sysopen()> に MASK 引数を使うことはほとんどないでしょう。
1068これは、新しいファイルにどのパーミッションを与えるかというユーザーの
1069自由を奪います。
1070選択を拒むということは、ほとんど常に悪いことです。
1071一つの例外は、メールフォルダ、クッキーファイル、内部用一時ファイルのような、
1072微妙な、あるいはプライベートなデータを保管する場合でしょう。
1073
1074=head1 Obscure Open Tricks
1075
1076(わかりにくい開くときの小技)
1077
1078=head2 Re-Opening Files (dups)
1079
1080(ファイルを再び開く(dup))
1081
1082=begin original
1083
1084Sometimes you already have a filehandle open, and want to make another
1085handle that's a duplicate of the first one. In the shell, we place an
1086ampersand in front of a file descriptor number when doing redirections.
1087For example, C<< 2>&1 >> makes descriptor 2 (that's STDERR in Perl)
1088be redirected into descriptor 1 (which is usually Perl's STDOUT).
1089The same is essentially true in Perl: a filename that begins with an
1090ampersand is treated instead as a file descriptor if a number, or as a
1091filehandle if a string.
1092
1093=end original
1094
1095既に開いているファイルハンドルを持っている時に、これを複製して
1096もう一つのハンドルがほしくなる場合がときどきあります。
1097シェルでは、リダイレクトをするときにファイル記述子番号の前に
1098アンパサンドを置きます。
1099例えば C<< 2>&1 >> は、記述子 2 (これは Perl では STDERR) を
1100記述子 1 (これは Perl では普通は STDOUT) にリダイレクトします。
1101同じことは Perl でも基本的には真です: アンパサンドで始まるファイル名は、
1102それが数値ならファイル記述子、文字列ならファイルハンドルとして
1103扱われます。
1104
1105 open(SAVEOUT, ">&SAVEERR") || die "couldn't dup SAVEERR: $!";
1106 open(MHCONTEXT, "<&4") || die "couldn't dup fd4: $!";
1107
1108=begin original
1109
1110That means that if a function is expecting a filename, but you don't
1111want to give it a filename because you already have the file open, you
1112can just pass the filehandle with a leading ampersand. It's best to
1113use a fully qualified handle though, just in case the function happens
1114to be in a different package:
1115
1116=end original
1117
1118これは、もし関数がファイル名を想定しているけれども、既にファイルは
1119開いているのでファイル名を渡したくない場合、単に先頭にアンパサンドを
1120付けたファイルハンドルを渡せるということを意味します。
1121しかし、万が一関数がたまたま違うパッケージだったときのために、完全修飾した
1122ハンドルを渡すのが最善です:
1123
1124 somefunction("&main::LOGFILE");
1125
1126=begin original
1127
1128This way if somefunction() is planning on opening its argument, it can
1129just use the already opened handle. This differs from passing a handle,
1130because with a handle, you don't open the file. Here you have something
1131you can pass to open.
1132
1133=end original
1134
1135この方法により、somefunction() が引数の値を開いた場合、
1136単に既に開いているハンドルを使えます。
1137これはハンドルを渡すのとは違います; なぜならハンドルではファイルを
1138開かないからです。
1139こちらでは開くときに指定できるものが指定できます。
1140238
1141239=begin original
1142240
1143If you have one of those tricky, newfangled I/O objects that the C++
241You can also just quickly C<die> on an undefined value this way:
1144folks are raving about, then this doesn't work because those aren't a
1145proper filehandle in the native Perl sense. You'll have to use fileno()
1146to pull out the proper descriptor number, assuming you can:
1147242
1148243=end original
1149244
1150もしC++ 民が夢中になっているような巧妙で目新 I/O オブジェクトの一つを
245また次のようて単に未定義値に対してすばやく C<die> することもできます:
1151使っているなら、これらはネイティブな Perl 的に適切なファイルハンドルでは
1152ないので、上述のような方法は動作しません。
1153適切な記述子番号を得るために fileno() を使う必要があります; それが出来ると
1154仮定すれば:
1155246
1156 use IO::Socket;
247 $line = <$handle> // die "no input found";
1157 $handle = IO::Socket::INET->new("www.perl.com:80");
1158 $fd = $handle->fileno;
1159 somefunction("&$fd"); # not an indirect function call
1160248
1161249=begin original
1162250
1163It can be easier (and certainly will be faster) just to use real
251However, if hitting EOF is an expected and normal event, you do not want to
1164filehandles though:
252exit simply because you have run out of input. Instead, you probably just want
253to exit an input loop. You can then test to see if an actual error has caused
254the loop to terminate, and act accordingly:
1165255
1166256=end original
1167257
1168しかし、普通ファイルハンドルを使う方簡単でしょう
258しかし、EOF 到達するのが想定されていて通常の出来事の場合は、
1169(そして確実に高速す):
259入力がなくなっただけ終了したくありません。
260そうではなく、単に入力ループを終了したいでしょう。
261実際のエラーがループを終了させたのかをテストして、適切に行動できます:
1170262
1171 use IO::Socket;
263 while (<$handle>) {
1172 local *REMOTE = IO::Socket::INET->new("www.perl.com:80");
264 # do something with data in $_
1173 die "can't connect" unless defined(fileno(REMOTE));
265 }
1174 somefunction("&main::REMOTE");
266 if ($!) {
267 die "unexpected error while reading from $filename: $!";
268 }
1175269
1176270=begin original
1177271
1178If the filehandle or descriptor number is preceded not just with a simple
272B<A Note on Encodings>: Having to specify the text encoding every time
1179"&" but rather with a "&=" combination, then Perl will not create a
273might seem a bit of a bother. To set up a default encoding for C<open> so
1180completely new descriptor opened to the same place using the dup(2)
274that you don't have to supply it each time, you can use the C<open> pragma:
1181system call. Instead, it will just make something of an alias to the
1182existing one using the fdopen(3S) library call. This is slightly more
1183parsimonious of systems resources, although this is less a concern
1184these days. Here's an example of that:
1185275
1186276=end original
1187277
1188もしファイルハドルや記述子番号の前のが単なる "&" ではなく "&=" の
278B<エコーディング関す注意>: テキストエンコーディングを毎回指定する
1189組み合わせ場合、Perl dup(2) システムコールを使って同場所で開いた
279必要があるのは少し面倒に感るかもしれません。
1190完全に新し記述子は作りません。
280毎回設定する必要がなように C<open> のためのデフォルトエンコーディングを
1191代わりに、fdopen(3S)イブラリコールを使ってでにある記述子の別名的な
281設定するために、C<open> グマを使えま:
1192ものを作ります。
1193これはシステムのリソースを少しケチることが出来ますが、最近ではこれは
1194あまり関心を持たれなくなりました。
1195以下はこの例です:
1196282
1197 $fd = $ENV{"MHCONTEXTFD"};
283 use open qw< :encoding(UTF-8) >;
1198 open(MHCONTEXT, "<&=$fd") or die "couldn't fdopen $fd: $!";
1199284
1200285=begin original
1201286
1202If you're using magic C<< <ARGV> >>, you could even pass in as a
287Once you've done that, you can safely omit the encoding part of the
1203command line argument in @ARGV something like C<"<&=$MHCONTEXTFD">,
288open mode:
1204but we've never seen anyone actually do this.
1205289
1206290=end original
1207291
1208もしマジカルな C<< <ARGV> >> 使っているならC<"<&=$MHCONTEXTFD">
292一度これ行えばopen モードからエンコーディング部分を安全に省略できます:
1209ような感じで @ARGV 内のコマンドライン引数として渡すことすら可能ですが、
1210実際にこれをしている人を見たことはありません。
1211
1212=head2 Dispelling the Dweomer
1213
1214(魔法を解く)
1215
1216=begin original
1217
1218Perl is more of a DWIMmer language than something like Java--where DWIM
1219is an acronym for "do what I mean". But this principle sometimes leads
1220to more hidden magic than one knows what to do with. In this way, Perl
1221is also filled with I<dweomer>, an obscure word meaning an enchantment.
1222Sometimes, Perl's DWIMmer is just too much like dweomer for comfort.
1223
1224=end original
1225293
1226Perl は、Java のような言語よりも「空気を読む」(DWIM)言語です --
294 open($handle, "<", $filename)
1227DWIM とは "do what I mean" の略です。
295 || die "$0: can't open $filename for reading: $!";
1228しかし、この原則は時々利用者が知っている以上の隠れた動作をすることが
1229あります。
1230こんな風に、Perl は (魔法を意味する不明確な単語である) I<dweomer> にも
1231満ちています。
1232時々、Perl の空気の読み方は快適さのために魔法のようになります。
1233296
1234297=begin original
1235298
1236If magic C<open> is a bit too magical for you, you don't have to turn
299But never use the bare C<< "<" >> without having set up a default encoding
1237to C<sysopen>. To open a file with arbitrary weird characters in
300first. Otherwise, Perl cannot know which of the many, many, many possible
1238it, it's necessary to protect any leading and trailing whitespace.
301flavors of text file you have, and Perl will have no idea how to correctly
1239Leading whitespace is protected by inserting a C<"./"> in front of a
302map the data in your file into actual characters it can work with. Other
1240filename that starts with whitespace. Trailing whitespace is protected
303common encoding formats including C<"ASCII">, C<"ISO-8859-1">,
1241by appending an ASCII NUL byte (C<"\0">) at the end of the string.
304C<"ISO-8859-15">, C<"Windows-1252">, C<"MacRoman">, and even C<"UTF-16LE">.
305See L<perlunitut> for more about encodings.
1242306
1243307=end original
1244308
1245マジカルな C<open> があなたとってちょっとマジカルするとしても、
309かし、先デフォトのエンコーディングを設定するなく裸の
1246C<sysopen> にまで戻る必要ありません
310C<< "<" >> を使うこと決してしないでください
1247ファイル名にどん変な文字が含まれてるファイルでも開くためには、
311さもば、Perl はともとてもとてもたくさんあテキストファイル
1248先頭と末尾空白保護す必要があります。
312種類うちどれかことできず、Perl はなたのファイルのデータを
1249先頭の空白は、空白で始まファイル名 C<"./"> を挿入することで
313動作させため実際の文字マッピングすることきません。
1250保護します。
314その他のよくあるエンコーディング形式には
1251末尾の空白は、文字列の末尾に ASCII NUL バイト (C<"\0">) を
315C<"ASCII">, C<"ISO-8859-1">,
1252追加することで保護します。
316C<"ISO-8859-15">, C<"Windows-1252">, C<"MacRoman"> および、
317C<"UTF-16LE"> すらもあります。
1254 $file =~ s#^(\s)#./$1#;
318エンコーディングに関するさらなる情報については L<perlunitut>
1255 open(FH, "< $file\0") || die "can't open $file: $!";
319参照してください。
1256
1257=begin original
1258
1259This assumes, of course, that your system considers dot the current
1260working directory, slash the directory separator, and disallows ASCII
1261NULs within a valid filename. Most systems follow these conventions,
1262including all POSIX systems as well as proprietary Microsoft systems.
1263The only vaguely popular system that doesn't work this way is the
1264"Classic" Macintosh system, which uses a colon where the rest of us
1265use a slash. Maybe C<sysopen> isn't such a bad idea after all.
1266320
1267=end original
321=head2 Opening Text Files for Writing
1268322
1269これはもちろん、あなたのシスムが "." をカレンディレクトリ、
323(書き込み用にキスファイルを開く)
1270"/" をディレクトリの区切りとして扱い、ASCII NUL をファイル名として
1271認めていないということを仮定しています。
1272全ての POSIX システムとプロプリエタリの Microsoft システムを含む、
1273ほとんどのシステムはこの慣例に従っています。
1274これに従わない、一般的に有名な唯一のシステムは
1275"Classic" Macintosh システムです; これは他のシステムが "/" を
1276使っているところで ":" を使います。
1277おそらく、とにかく C<sysopen> を使うということはそれほど悪い考えでは
1278ありません。
1279324
1280325=begin original
1281326
1282If you want to use C<< <ARGV> >> processing in a totally boring
327When you want to write to a file, you first have to decide what to do about
1283and non-magical way, you could do this first:
328any existing contents of that file. You have two basic choices here: to
329preserve or to clobber.
1284330
1285331=end original
1286332
1287もしC<< <ARGV> >> 処理、本当に退屈つマジカルでない方法で
333ファイルに書き込みたい場合ファイルの既存の内容どうする
1288行いたいなら、まず以下のようにできます:
334まず決定する必要があります
335二つの基本的な選択肢があります: 保存するか上書きするかです。
1290 # "Sam sat on the ground and put his head in his hands.
1291 # 'I wish I had never come here, and I don't want to see
1292 # no more magic,' he said, and fell silent."
1293 for (@ARGV) {
1294 s#^([^./])#./$1#;
1295 $_ .= "\0";
1296 }
1297 while (<>) {
1298 # now process $_
1299 }
1300336
1301337=begin original
1302338
1303But be warned that users will not appreciate being unable to use "-"
339If you want to preserve any existing contents, then you want to open the file
1304to mean standard input, per the standard convention.
340in append mode. As in the shell, in Perl you use C<<< ">>" >>> to open an
341existing file in append mode. C<<< ">>" >>> creates the file if it does not
342already exist.
1305343
1306344=end original
1307345
1308し、ユーザーは、標準入力意味るために "-" を使うという一般的な
346既存の内容を保存たい場合ファイル追記モードで開きま
1309慣習が使えないいうこと喜ばないだろうということは
347シェル同様に、 Perl でも既存のファイル追記モードで開くために
1310警告しておきます。
348C<<< ">>" >>> が使われます。
349ファイルがない場合、C<<< ">>" >>> はファイルを作ります。
1312=head2 Paths as Opens
1313350
1314(open にパスを)
351 my $handle = undef;
352 my $filename = "/some/path/to/a/textfile/goes/here";
353 my $encoding = ":encoding(UTF-8)";
1315354
1316=begin original
355 open($handle, ">> $encoding", $filename)
356 || die "$0: can't open $filename for appending: $!";
1318You've probably noticed how Perl's C<warn> and C<die> functions can
1319produce messages like:
1320
1321=end original
1322
1323どうやって Perl の C<warn> 関数と C<die> 関数が以下のようなメッセージを
1324生成するかに気付いたでしょう:
1325
1326 Some warning at scriptname line 29, <FH> line 7.
1327357
1328358=begin original
1329359
1330That's because you opened a filehandle FH, and had read in seven records
360Now you can write to that filehandle using any of C<print>, C<printf>,
1331from it. But what was the name of the file, rather than the handle?
361C<say>, C<write>, or C<syswrite>.
1332362
1333363=end original
1334364
1335これは、あなたがファイルハンドル FH を開い、そこから 7 レコードを
365これでこのハンドルに対しC<print>, C<printf>,
1336読みんだからです。
366C<say>, C<write>, C<syswrite> を使って書きめます。
1337しかし、ハンドルではなく、ファイル名はどうでしょう?
1338367
1339368=begin original
1340369
1341If you aren't running with C<strict refs>, or if you've turned them off
370As noted above, if the file does not already exist, then the append-mode open
1342temporarily, then all you have to do is this:
371will create it for you. But if the file does already exist, its contents are
372safe from harm because you will be adding your new text past the end of the
373old text.
1343374
1344375=end original
1345376
1346 C<strict refs> を有効していないか一時的無効にしてい
377前述たように、ファイルが既存在していない場合追記モードで開くと
1347る必要があるのは以下のことだけです:
378ファイルを作りま
379しかしファイルが既に存在している場合、その内容は保護されます; 新しいテキストは
1349 open($path, "< $path") || die "can't open $path: $!";
380既存のテキストの末尾に追加されるからです。
1350 while (<$path>) {
1351 # whatever
1352 }
1353381
1354382=begin original
1355383
1356Since you're using the pathname of the file as its handle,
384On the other hand, sometimes you want to clobber whatever might already be
1357you'll get warnings more like
385there. To empty out a file before you start writing to it, you can open it
386in write-only mode:
1358387
1359388=end original
1360389
1361ファイルのパス名をハンドルとして使っているので、以下のような警告が
390一方、時々、既に何かがあっても上書きしたときもあります。
1362出ま
391書き込みを始める前にファイルを消ために、書き込み専用モードで
392開くことができます:
1364 Some warning at scriptname line 29, </etc/motd> line 7.
1365393
1366=head2 Single Argument Open
394 my $handle = undef;
395 my $filename = "/some/path/to/a/textfile/goes/here";
396 my $encoding = ":encoding(UTF-8)";
1367397
1368(1 引数の open)
398 open($handle, "> $encoding", $filename)
399 || die "$0: can't open $filename in write-open mode: $!";
1369400
1370401=begin original
1371402
1372Remember how we said that Perl's open took two arguments? That was a
403Here again Perl works just like the shell in that the C<< ">" >> clobbers
1373passive prevarication. You see, it can also take just one argument.
404an existing file.
1374If and only if the variable is a global variable, not a lexical, you
1375can pass C<open> just one argument, the filehandle, and it will
1376get the path from the global scalar variable of the same name.
1377405
1378406=end original
1379407
1380Perl の open 2 引数取ると言ったことを覚えていますか?
408ここで再び Perl はシェルと同様に動作し、C<< ">" >> は既存のファイル
1381これは消極的なごまかす。
409上書きす。
1382ほら、単に 1 引数を取ることもできます。
1383変数がレキシカルではなくグローバルな変数の場合にのみ、C<open> に
13841 引数だけ(ファイルハンドル)を渡すことができます; こうすると、
1385同じ名前を持つグローバルなスカラ変数からパスを取ります。
1386
1387 $FILE = "/etc/motd";
1388 open FILE or die "can't open $FILE: $!";
1389 while (<FILE>) {
1390 # whatever
1391 }
1392410
1393411=begin original
1394412
1395Why is this here? Someone has to cater to the hysterical porpoises.
413As with the append mode, when you open a file in write-only mode,
1396It's something that's been in Perl since the very beginning, if not
414you can now write to that filehandle using any of C<print>, C<printf>,
1397before.
415C<say>, C<write>, or C<syswrite>.
1398416
1399417=end original
1400418
1401どうしてこれはここなんしょう?
419追記モードと同様に、ファイルを書き込みモード開くと、
1402誰かがヒステリックなネズミイルカの要求満たす必要があります。
420C<print>, C<printf>, C<say>, C<write>, C<syswrite> 使って
1403これは(遅くとも)非常初期から Perl ります。
421ファイルハンドル書き込めるようります。
1404
1405=head2 Playing with STDIN and STDOUT
1406
1407(STDIN と STDOUT を扱う)
1408422
1409423=begin original
1410424
1411One clever move with STDOUT is to explicitly close it when you're done
425What about read-write mode? You should probably pretend it doesn't exist,
1412with the program.
426because opening text files in read-write mode is unlikely to do what you
427would like. See L<perlfaq5> for details.
1413428
1414429=end original
1415430
1416STDOUT 関する一の利口な行動、プログラムの終了時に
431読み書きモードについて?
1417明示的に閉じることです。
432おそらくそれは存在しないいうふりをした方がよいしょう;
433なぜならテキストファイルを読み書きモードで開いても
434おそらくあなたが望んでいることをしないからです。
435詳しくは L<perlfaq5> を参照してください。
1418436
1419 END { close(STDOUT) || die "can't close stdout: $!" }
437=head1 Opening Binary Files
1420
1421=begin original
1422438
1423If you don't do this, and your program fills up the disk partition due
439(バイナリファイルを開く)
1424to a command line redirection, it won't report the error exit with a
1425failure status.
1426
1427=end original
1428
1429これをしないままで、このプログラムがコマンドラインリダイレクトによって
1430ディスクをいっぱいにしてしまっても、失敗状態でエラー終了しません。
1431440
1432441=begin original
1433442
1434You don't have to accept the STDIN and STDOUT you were given. You are
443If the file to be opened contains binary data instead of text characters,
1435welcome to reopen them if you'd like.
444then the C<MODE> argument to C<open> is a little different. Instead of
445specifying the encoding, you tell Perl that your data are in raw bytes.
1436446
1437447=end original
1438448
1439与えられた STDIN STDOUT を受け入れ必要ありせん。
449開こうしていファイルがテキスト文字でなくバイナリデータが含れている
1440望むら、これらを開き直せます。
450場合、C<open> の C<MODE> 引数は少るものになります。
451エンコーディングを指定する代わりに、データが生のバイト列であることを
1442 open(STDIN, "< datafile")
452Perl に知らせます。
1443 || die "can't open datafile: $!";
1444453
1445 open(STDOUT, "> output")
454 my $filename = "/some/path/to/a/binary/file/goes/here";
1446 || die "can't open output: $!";
455 my $encoding = ":raw :bytes"
456 my $handle = undef; # this will be filled in on success
1447457
1448458=begin original
1449459
1450And then these can be accessed directly or passed on to subprocesses.
460And then open as before, choosing C<<< "<" >>>, C<<< ">>" >>>, or
1451This makes it look as though the program were initially invoked
461C<<< ">" >>> as needed:
1452with those redirections from the command line.
1453462
1454463=end original
1455464
1456それからこれらは直接アクセスした子プロセス渡したりできます。
465それから前述の通、必要応じて
1457これらは、プログラムの起動時にコマンドラインからリダイレクトが
466C<<< "<" >>>, C<<< ">>" >>>, C<<< ">" >>> を選びます:
1458与えられたかのように動作します。
1459467
1460=begin original
468 open($handle, "< $encoding", $filename)
469 || die "$0: can't open $filename for reading: $!";
1462It's probably more interesting to connect these to pipes. For example:
1463
1464=end original
1465470
1466これらをパイプにつなぐ方がより興味深いでしょう。
471 open($handle, ">> $encoding", $filename)
1467例えば:
472 || die "$0: can't open $filename for appending: $!";
1468473
1469 $pager = $ENV{PAGER} || "(less || more)";
474 open($handle, "> $encoding", $filename)
1470 open(STDOUT, "| $pager")
475 || die "$0: can't open $filename in write-open mode: $!";
1471 || die "can't fork a pager: $!";
1472476
1473477=begin original
1474478
1475This makes it appear as though your program were called with its stdout
479Alternately, you can change to binary mode on an existing handle this way:
1476already piped into your pager. You can also use this kind of thing
1477in conjunction with an implicit fork to yourself. You might do this
1478if you would rather handle the post processing in your own program,
1479just in a different process:
1480480
1481481=end original
1482482
1483これによってプログラム標準出力がが既にページャとパプで
483あるいはようにして既に存在しているハンドルをバナリモードに
1484つながれているかのように見えます
484ることが出来ます:
1485このようなことはまた、自分自身を暗黙に fork したものと結合するためにも
1486使えます。
1487自分自身のプログラムの別のプロセスでで後処理を扱いたい場合、
1488以下のようにできます:
1489485
1490 head(100);
486 binmode($handle) || die "cannot binmode handle";
1491 while (<>) {
1492 print;
1493 }
1494
1495 sub head {
1496 my $lines = shift || 20;
1497 return if $pid = open(STDOUT, "|-"); # return if parent
1498 die "cannot fork: $!" unless defined $pid;
1499 while (<STDIN>) {
1500 last if --$lines < 0;
1501 print;
1502 }
1503 exit;
1504 }
1505487
1506488=begin original
1507489
1508This technique can be applied to repeatedly push as many filters on your
490This is especially handy for the handles that Perl has already opened for you.
1509output stream as you wish.
1510491
1511492=end original
1512493
1513のテクニックは、繰り返しプッシュすことで、出力ストリーム好きなだけ
494は、Perl が既に開いていハンドル対して特に有用です。
1514多くのフィルタを適用できます。
1515
1516=head1 Other I/O Issues
1517495
1518(その他の I/O 関連の話題)
496 binmode(STDIN) || die "cannot binmode STDIN";
497 binmode(STDOUT) || die "cannot binmode STDOUT";
1519498
1520499=begin original
1521500
1522These topics aren't really arguments related to C<open> or C<sysopen>,
501You can also pass C<binmode> an explicit encoding to change it on the fly.
1523but they do affect what you do with your open files.
502This isn't exactly "binary" mode, but we still use C<binmode> to do it:
1524503
1525504=end original
1526505
1527これら話題は実際 C<open> や C<sysopen> に関連したものではありませんが、
506また、そ場で変更するために C<binmode> に明示的にエンコーディングを
1528ファイルを開くときに行うことに影響を与えます。
507渡すこともできます。
508これは正確には「バイナリ」モードではありませんが、それでも
509これをするために C<binmode> を使います:
1529510
1530=head2 Opening Non-File Files
511 binmode(STDIN, ":encoding(MacRoman)") || die "cannot binmode STDIN";
512 binmode(STDOUT, ":encoding(UTF-8)") || die "cannot binmode STDOUT";
1532(ファイルでないファイルを開く)
1533513
1534514=begin original
1535515
1536When is a file not a file? Well, you could say when it exists but
516Once you have your binary file properly opened in the right mode, you can
1537isn't a plain file. We'll check whether it's a symbolic link first,
517use all the same Perl I/O functions as you used on text files. However,
1538just in case.
518you may wish to use the fixed-size C<read> instead of the variable-sized
519C<readline> for your input.
1539520
1540521=end original
1541522
1542ファイルファイルでないときは?
523一旦バイナリファイルを正しいモードで適切に開くと、テキストファイルで
1543と、プレーンファイルでないものき、と言いたいんでよね
524使ものと全て同じ Perl I/O 関数を使えます。
1544まず念のため、それがシンボリックリンクかどうかを調べます。
525しかし入力対して可変長の C<readline> ではなく固定長の
526C<read> を使った方が良いでしょう。
1546 if (-l $file || ! -f _) {
1547 print "$file is not a plain file\n";
1548 }
1549527
1550528=begin original
1551529
1552What other kinds of files are there than, well, files? Directories,
530Here's an example of how to copy a binary file:
1553symbolic links, named pipes, Unix-domain sockets, and block and character
1554devices. Those are all files, too--just not I<plain> files. This isn't
1555the same issue as being a text file. Not all text files are plain files.
1556Not all plain files are text files. That's why there are separate C<-f>
1557and C<-T> file tests.
1558531
1559532=end original
1560533
1561えーと、ファイル他にどんな種類のファイルがあしょう?
534はバイナリファイルをコピーすす:
1562ディレクトリ、シンボリックリンク、名前付きパイプ、Unix ドメインソケット、
1563キャラクタデバイス、ブロックデバイスです。
1564これらも全てファイルです -- 単に I<プレーン> ファイルではないと
1565いうだけです。
1566これはテキストファイルと同じ問題ではありません。
1567全てのテキストファイルがプレーンファイルではありません。
1568全てのプレーンファイルがテキストファイルではありません。
1569これが、C<-f> と C<-T> のファイルテストが分離している理由です。
1570535
1571=begin original
536 my $BUFSIZ = 64 * (2 ** 10);
537 my $name_in = "/some/input/file";
1573To open a directory, you should use the C<opendir> function, then
538 my $name_out = "/some/output/flie";
1574process it with C<readdir>, carefully restoring the directory
1575name if necessary:
1576539
1577=end original
540 my($in_fh, $out_fh, $buffer);
1578541
1579ディレクトリを開くには、C<opendir> 関数を使って、それから
542 open($in_fh, "<", $name_in)
1580C<readdir> で処理します; もし必要なら注意深くディレクトリ名を復元します:
543 || die "$0: cannot open $name_in for reading: $!";
544 open($out_fh, ">", $name_out)
545 || die "$0: cannot open $name_out for writing: $!";
1581546
1582 opendir(DIR, $dirname) or die "can't opendir $dirname: $!";
547 for my $fh ($in_fh, $out_fh) {
1583 while (defined($file = readdir(DIR))) {
548 binmode($fh) || die "binmode failed";
1584 # do something with "$dirname/$file"
1585549 }
1586 closedir(DIR);
1587
1588=begin original
1589
1590If you want to process directories recursively, it's better to use the
1591File::Find module. For example, this prints out all files recursively
1592and adds a slash to their names if the file is a directory.
1593
1594=end original
1595
1596ディレクトリを再帰的に処理したい場合は、File::Find モジュールを使った方が
1597いいでしょう。
1598例えば、これは全てのファイルを再帰的に表示して、もしファイルが
1599ディレクトリの場合は末尾にスラッシュを追加します。
1600
1601 @ARGV = qw(.) unless @ARGV;
1602 use File::Find;
1603 find sub { print $File::Find::name, -d && '/', "\n" }, @ARGV;
1604
1605=begin original
1606
1607This finds all bogus symbolic links beneath a particular directory:
1608
1609=end original
1610
1611以下は、特定のディレクトリ以下から偽のシンボリックリンクを全て探します:
1612
1613 find sub { print "$File::Find::name\n" if -l && !-e }, $dir;
1614
1615=begin original
1616
1617As you see, with symbolic links, you can just pretend that it is
1618what it points to. Or, if you want to know I<what> it points to, then
1619C<readlink> is called for:
1620
1621=end original
1622
1623上述したように、シンボリックリンクの場合、単にそれが指しているもの振りを
1624することができます。
1625あるいは、もしそれが I<何を> 指しているのかを知りたい場合は、
1626C<readlink> を呼び出します:
1627
1628 if (-l $file) {
1629 if (defined($whither = readlink($file))) {
1630 print "$file points to $whither\n";
1631 } else {
1632 print "$file points nowhere: $!\n";
1633 }
1634 }
1635
1636=head2 Opening Named Pipes
1637
1638(名前付きパイプを開く)
1639
1640=begin original
1641
1642Named pipes are a different matter. You pretend they're regular files,
1643but their opens will normally block until there is both a reader and
1644a writer. You can read more about them in L<perlipc/"Named Pipes">.
1645Unix-domain sockets are rather different beasts as well; they're
1646described in L<perlipc/"Unix-Domain TCP Clients and Servers">.
1647
1648=end original
1649
1650名前付きパイプは別の問題です。
1651これらは普通のファイルのように振る舞いますが、この open は普通
1652読み込み側と書き込み側の両方ができるまでブロックされます。
1653これらについては L<perlipc/"Named Pipes"> でより多くのことを
1654読むことができます。
1655Unix ドメインソケットは同様にやや違うものです;
1656これらは L<perlipc/"Unix-Domain TCP Clients and Servers"> に
1657記述されています。
1658
1659=begin original
1660
1661When it comes to opening devices, it can be easy and it can be tricky.
1662We'll assume that if you're opening up a block device, you know what
1663you're doing. The character devices are more interesting. These are
1664typically used for modems, mice, and some kinds of printers. This is
1665described in L<perlfaq8/"How do I read and write the serial port?">
1666It's often enough to open them carefully:
1667
1668=end original
1669
1670デバイスを開くときは、簡単にもなりますしトリッキーにもなります。
1671ブロックデバイスを開こうとしているなら、何をしようとしているのか
1672分かっていることを仮定します。
1673キャラクタデバイスはもっと興味深いです。
1674これらは典型的にはモデム、マウス、ある種のプリンタのために使われます。
1675これは L<perlfaq8/"How do I read and write the serial port?"> に
1676記述されています。
1677しばしば慎重に開くだけで充分です:
1678
1679 sysopen(TTYIN, "/dev/ttyS1", O_RDWR | O_NDELAY | O_NOCTTY)
1680 # (O_NOCTTY no longer needed on POSIX systems)
1681 or die "can't open /dev/ttyS1: $!";
1682 open(TTYOUT, "+>&TTYIN")
1683 or die "can't dup TTYIN: $!";
1684
1685 $ofh = select(TTYOUT); $| = 1; select($ofh);
1686
1687 print TTYOUT "+++at\015";
1688 $answer = <TTYIN>;
1689
1690=begin original
1691
1692With descriptors that you haven't opened using C<sysopen>, such as
1693sockets, you can set them to be non-blocking using C<fcntl>:
1694
1695=end original
1696
1697ソケットのように、C<sysopen> を使わずに開いた記述子の場合は、
1698C<fcntl> を使って非ブロックモードに設定できます:
1699
1700 use Fcntl;
1701 my $old_flags = fcntl($handle, F_GETFL, 0)
1702 or die "can't get flags: $!";
1703 fcntl($handle, F_SETFL, $old_flags | O_NONBLOCK)
1704 or die "can't set non blocking: $!";
1705
1706=begin original
1707
1708Rather than losing yourself in a morass of twisting, turning C<ioctl>s,
1709all dissimilar, if you're going to manipulate ttys, it's best to
1710make calls out to the stty(1) program if you have it, or else use the
1711portable POSIX interface. To figure this all out, you'll need to read the
1712termios(3) manpage, which describes the POSIX interface to tty devices,
1713and then L<POSIX>, which describes Perl's interface to POSIX. There are
1714also some high-level modules on CPAN that can help you with these games.
1715Check out Term::ReadKey and Term::ReadLine.
1716550
1717=end original
551 while (read($in_fh, $buffer, $BUFSIZ)) {
552 unless (print $out_fh $buffer) {
1719もし tty を操作しようとしているなら、全く異なる C<ioctl> の泥沼に
553 die "couldn't write to $name_out: $!";
1720迷い込むのではなく、もし stty(1) プログラムがあるならこれを呼び出して、
554 }
1721さもなければ移植性のある POSIX インターフェースを使うのが最善です。
555 }
1722これらのこと全てを理解するには、まず tty デバイスへの POSIX
1723インターフェースについて記述している termios(3) man ページを読んで、次に
1724POSIX への Perl のインターフェースについて記述している L<POSIX> を
1725読む必要があります。
1726これらのものを扱う助けになるような高レベルモジュールも CPAN にあります。
1727Term::ReadKey と Term::ReadLine を調べてください。
1728
1729=head2 Opening Sockets
1730
1731(ソケットを開く)
1732
1733=begin original
1734556
1735What else can you open? To open a connection using sockets, you won't use
557 close($in_fh) || die "couldn't close $name_in: $!";
1736one of Perl's two open functions. See
558 close($out_fh) || die "couldn't close $name_out: $!";
1737L<perlipc/"Sockets: Client/Server Communication"> for that. Here's an
1738example. Once you have it, you can use FH as a bidirectional filehandle.
1739559
1740=end original
560=head1 Opening Pipes
1741561
1742他の何を開けるの?
562(パイプを開く)
1743ソケットを使った接続を開くには、Perl の 2 つの open 関数のどちらも
1744使いません。
1745そのためには L<perlipc/"Sockets: Client/Server Communication"> を
1746参照してください。
1747以下は例です。
1748これを実行すると、FH を双方向ファイルハンドルとして使えます。
1749
1750 use IO::Socket;
1751 local *FH = IO::Socket::INET->new("www.perl.com:80");
1752563
1753564=begin original
1754565
1755For opening up a URL, the LWP modules from CPAN are just what
566Perl also lets you open a filehandle into an external program or shell
1756the doctor ordered. There's no filehandle interface, but
567command rather than into a file. You can do this in order to pass data
1757it's still easy to get the contents of a document:
568from your Perl program to an external command for further processing, or
569to receive data from another program for your own Perl program to
570process.
1758571
1759572=end original
1760573
1761URL を開くには、CPAN にある LWP モジューがぴったりす。
574Perlまたファイルではなく外部プログラムやシェルコマンドへの
1762ファイルハンドルのインターフェースはないでが、
575ファイルハンドルも開きま
1763でも簡単に文書の中身れま:
576れを、更なる処理のために Perl プログラムか外部コマンドへ渡ため、
577または処理する Perl プログラムのために他のプログラムからデータを
1765 use LWP::Simple;
578受け取るために行えます。
1766 $doc = get('http://www.cpan.org/');
1767
1768=head2 Binary Files
1769
1770(バイナリファイル)
1771579
1772580=begin original
1773581
1774On certain legacy systems with what could charitably be called terminally
582Filehandles into commands are also known as I<pipes>, since they work on
1775convoluted (some would say broken) I/O models, a file isn't a file--at
583similar inter-process communication principles as Unix pipelines. Such a
1776least, not with respect to the C standard I/O library. On these old
584filehandle has an active program instead of a static file on its
1777systems whose libraries (but not kernels) distinguish between text and
585external end, but in every other sense it works just like a more typical
1778binary streams, to get files to behave properly you'll have to bend over
586file-based filehandle, with all the techniques discussed earlier in this
1779backwards to avoid nasty problems. On such infelicitous systems, sockets
587article just as applicable.
1780and pipes are already opened in binary mode, and there is currently no
1781way to turn that off. With files, you have more options.
1782588
1783589=end original
1784590
1785最終的に (壊れていると言われる) I/O モデルに巻き込まれる寛大に
591コマンドへのファイルハンドルは、I<パイプ>して知られます;
1786呼ばれるある種の古いシステムでは、ファルはファルではありません --
592Unix パプランという似たようなプロセス間通信原則に基づいて
1787少なくとも C 標準 I/O ライブラリという観点
593動作するから
1788(カーネルではなく)ライブラリがテキストストリームとバイナリストリームを
594そのようなファイハンドルは、外側が静的なファイルではなく
1789区別するような古いシステムで適切振る舞うようにファイルを
595動作中のプログラムですがそれ以外の点ついては
1790取得するためには、不愉快問題を避けるため懸命な努力が必要です。
596より典型的ファイルベースのファイルハンドルとちょうど同じよう
1791このような不幸なシステムは、ソケットとパイプは既にバイナリモード
597動作し、この文書で既に議論した全てのテクニックが利用可能す。
1792開いていて、今のところこれをオフにする方法はありません。
1793ファイルに対しては、もっと選択肢があります。
1794598
1795599=begin original
1796600
1797Another option is to use the C<binmode> function on the appropriate
601As such, you open a pipe using the same C<open> call that you use for
1798handles before doing regular I/O on them:
602opening files, setting the second (C<MODE>) argument to special
603characters that indicate either an input or an output pipe. Use C<"-|"> for a
604filehandle that will let your Perl program read data from an external
605program, and C<"|-"> for a filehandle that will send data to that
606program instead.
1799607
1800608=end original
1801609
1802もう一つ選択肢は、通常の I/O を行う前、適切なファルハンドルに
6102 番目(C<MODE>) 引数プの入力または出力を示す特殊な文字を
1803C<binmode> 関数を使うことす:
611設定することで、ファイルを開くのに使うのと同じ C<open> で
612パイプを開きます。
1805 binmode(STDIN);
613Perl プログラムが外部プログラムからデータを読み込むファイルハンドルには
1806 binmode(STDOUT);
614C<"-|"> を使います; プログラムにデータを送るファイルハンドルには
1807 while (<STDIN>) { print }
615C<"|-"> を使います。
1808
1809=begin original
1810
1811Passing C<sysopen> a non-standard flag option will also open the file in
1812binary mode on those systems that support it. This is the equivalent of
1813opening the file normally, then calling C<binmode> on the handle.
1814
1815=end original
1816616
1817C<sysopen> に非標準フラグオプションを渡すことでも、そのような
617=head2 Opening a pipe for reading
1818システムでバイナリモードでファイルを開けます。
1819これは、ファイルを普通に開いてから、ハンドルに対して C<binmode> を
1820呼び出すのと等価です。
1821618
1822 sysopen(BINDAT, "records.data", O_RDWR | O_BINARY)
619(読み込み用にパイプを開く)
1823 || die "can't open records.data: $!";
1824620
1825621=begin original
1826622
1827Now you can use C<read> and C<print> on that handle without worrying
623Let's say you'd like your Perl program to process data stored in a nearby
1828about the non-standard system I/O library breaking your data. It's not
624directory called C<unsorted>, which contains a number of textfiles.
1829a pretty picture, but then, legacy systems seldom are. CP/M will be
625You'd also like your program to sort all the contents from these files
1830with us until the end of days, and after.
626into a single, alphabetically sorted list of unique lines before it
627starts processing them.
1831628
1832629=end original
1833630
1834これで、非標準シスム I/O ラブラリデータを壊す心配なしに
631たくさんのキストファ含まれている、C<unsorted> と呼ばれる
1835ハンドル対し C<read> と C<print> 使えようになりました。
632近くのディレクトリ保管されいるデータ処理す
1836これは美しい形ではありませんが、レガシーシステムは大抵そいうものです
633Perl プログラムが欲しいとしましょう。
1837CP/M は世界が終わるで(そしてその後も)我々と共にあでしょう。
634た、処理を開始す前に、複数のファイルを単一の、ユニークな行を
635アルファベット順にソートしたいとします。
1838636
1839637=begin original
1840638
1841On systems with exotic I/O systems, it turns out that, astonishingly
639You could do this through opening an ordinary filehandle into each of
1842enough, even unbuffered I/O using C<sysread> and C<syswrite> might do
640those files, gradually building up an in-memory array of all the file
1843sneaky data mutilation behind your back.
641contents you load this way, and finally sorting and filtering that array
642when you've run out of files to load. I<Or>, you could offload all that
643merging and sorting into your operating system's own C<sort> command by
644opening a pipe directly into its output, and get to work that much
645faster.
1844646
1845647=end original
1846648
1847風変わりな I/O システムを持つシステムでは、驚いたことに、
649それぞれのファイル対して通常のファイルハンドルを開き
1848C<sysread> や C<syswrite> を使ったバッファリングしない I/O でさえも
650このようにして読み込んだ全てのファイルの内容を徐々にメモ内の配列に
1849背後でこそりとデータ操作をすることがあります。
651構築し、読み込むファイルがなくなたら最後にソトとフィルリングをする
652という形でこれを行うことも出来ます。
1851 while (sysread(WHENCE, $buf, 1024)) {
653I<あるいは>、結合とソートをオペレーティング自身の C<sort> コマンドに
1852 syswrite(WHITHER, $buf, length($buf));
654任せて、その出力を直接パイプで開くことで、遙かに速く作業することも出来ます。
1853 }
1854655
1855656=begin original
1856657
1857Depending on the vicissitudes of your runtime system, even these calls
658Here's how that might look:
1858may need C<binmode> or C<O_BINARY> first. Systems known to be free of
1859such difficulties include Unix, the Mac OS, Plan 9, and Inferno.
1860659
1861660=end original
1862661
1863実行させるシステムの紆余曲折具合によっては、これシステムコールです
662以下は、これがどように見えるかです:
1864最初に C<binmode> や C<O_BINARY> が必要かもしれません。
1865このような問題がないと分かっているシステムには Unix, Mac OS, Plan 9,
1866Inferno などがあります。
1867
1868=head2 File Locking
1869663
1870(ファイルのロック)
664 open(my $sort_fh, '-|', 'sort -u unsorted/*.txt')
665 or die "Couldn't open a pipe into sort: $!";
1871666
1872=begin original
667 # And right away, we can start reading sorted lines:
668 while (my $line = <$sort_fh>) {
1874In a multitasking environment, you may need to be careful not to collide
669 #
1875with other processes who want to do I/O on the same files as you
670 # ... Do something interesting with each $line here ...
1876are working on. You'll often need shared or exclusive locks
671 #
1877on files for reading and writing respectively. You might just
672 }
1878pretend that only exclusive locks exist.
1879
1880=end original
1881
1882マルチタスク環境では、あなたが触ろうとしているファイルと同じファイルを
1883他のプロセスが衝突しないように気をつける必要があります。
1884しばしば、ファイルを読み込みまたは書き込みするために、それぞれ
1885共有ロックと排他ロックが必要になります。
1886あるいは、単に排他ロックしかないような振りをするかもしれません。
1887673
1888674=begin original
1889675
1890Never use the existence of a file C<-e $file> as a locking indication,
676The second argument to C<open>, C<"-|">, makes it a read-pipe into a
1891because there is a race condition between the test for the existence of
677separate program, rather than an ordinary filehandle into a file.
1892the file and its creation. It's possible for another process to create
1893a file in the slice of time between your existence check and your attempt
1894to create the file. Atomicity is critical.
1895678
1896679=end original
1897680
1898決して、ファイル存在 C<-e $file> をロック指示に使わないでください;
681C<open> 2 番目の引数である C<"-|"> は、ファイルへの通常の
1899なぜならファイルの存在テストとその作成の間競合条件があるからです。
682ファイルハンドルではなく、別個プログラムへ読み込みパイプします。
1900存在チェックとファイル作成のわずかな間に、他のプロセスがファイルを作る
1901可能性があります。
1902原子性は危機的です。
1903683
1904684=begin original
1905685
1906Perl's most portable locking interface is via the C<flock> function,
686Note that the third argument to C<open> is a string containing the
1907whose simplicity is emulated on systems that don't directly support it
687program name (C<sort>) plus all its arguments: in this case, C<-u> to
1908such as SysV or Windows. The underlying semantics may affect how
688specify unqiue sort, and then a fileglob specifying the files to sort.
1909it all works, so you should learn how C<flock> is implemented on your
689The resulting filehandle C<$sort_fh> works just like a read-only (C<<
1910system's port of Perl.
690"<" >>) filehandle, and your program can subsequently read data
691from it as if it were opened onto an ordinary, single file.
1911692
1912693=end original
1913694
1914Perl もっとも移植性あるロックインターフェースは、
695C<open> 3 番目引数は、
1915C<flock> 関数によるものです; この単純さは、SysV や Windows のような、
696プログラム名 (C<sort>) とそ全ての引数を含んだ文字列です:
1916れに直接対応していないシステムでもエミュレートています。
697の場合、C<-u> はユニクソーを指定し、そからファイルグロブは
1917基礎とな動作はれがどのようかに影響を与えるので、
698ソートすファイルを指定する注意してださい。
1918あなたが使うシステムPerl で C<flock> がどのように実装されているかを
699結果ファイルハンドル C<$sort_fh>
1919学ぶべきです。
700ちょうど読み込み専用 (C<< "<" >>) ファイルハンドルのように動作し、
701プログラムは、通常の単一のファイルが開かれたかのように、
1921=begin original
702引き続いてそこからデータを読み込むことができます。
1922
1923File locking I<does not> lock out another process that would like to
1924do I/O. A file lock only locks out others trying to get a lock, not
1925processes trying to do I/O. Because locks are advisory, if one process
1926uses locking and another doesn't, all bets are off.
1927703
1928=end original
704=head2 Opening a pipe for writing
1929705
1930ファルロックは、他のロセスが I/O 操作行うことからロックするもの
706(書き込み用にパイプを開く)
1931I<ではありません>。
1932ファイルロックは、他のプロセスの I/O 操作をロックするのではなく、他の
1933プロセスがロックを得ようとすることをロックします。
1934ロックは勧告的なので、あるプロセスがロックを使っていても、他の
1935プロセスがロックを使っていなければ、全ては台無しになります。
1936707
1937708=begin original
1938709
1939By default, the C<flock> call will block until a lock is granted.
710Continuing the previous example, let's say that your program has
1940A request for a shared lock will be granted as soon as there is no
711completed its processing, and the results sit in an array called
1941exclusive locker. A request for an exclusive lock will be granted as
712C<@processed>. You want to print these lines to a file called
1942soon as there is no locker of any kind. Locks are on file descriptors,
713C<numbered.txt> with a neatly formatted column of line-numbers.
1943not file names. You can't lock a file until you open it, and you can't
1944hold on to a lock once the file has been closed.
1945714
1946715=end original
1947716
1948デフォルトでは、C<flock> 呼び出、ロックが得られるまでブロックします。
717前回の例の続きとグラムの処理を完成させて、
1949共有ロック要求、誰も排他ロックを持っていない状態になれば直ちに
718結果 C<@processed> と呼ばれる配列に入っているとしましょう。
1950受け入れられます。
719れらの行を C<numbered.txt> というファイル名に、
1951排他ロック要求は、誰もあらゆる種類のロックを守って状態
720いい感じ整形さた行番号の列と共に出力したいとします。
1952与えられます。
1953ロックはファイル名に対してではなく、ファイル記述子について与えられます。
1954ファイルを開かずにファイルをロックすることはできませんし、ファイルを閉じた
1955後もロックを持ったままにすることもできません。
1956721
1957722=begin original
1958723
1959Here's how to get a blocking shared lock on a file, typically used
724Certainly you could write your own code to do this ? or, once again,
1960for reading:
725you could kick that work over to another program. In this case, C<cat>,
726running with its own C<-n> option to activate line numbering, should do
727the trick:
1961728
1962729=end original
1963730
1964以下はファイル対してブロックする共有ロック得る方法で、
731確かこれをするコード自分書くこともできます - あるいは、再び
1965典型的は読み込み時に使われます:
732この作業を他のプログラム送ることもできます
733この場合、C<cat> を、行番号付けを有効にする C<-n> オプション込みで
734実行するには、次の技を使います:
1966735
1967 use 5.004;
736 open(my $cat_fh, '|-', 'cat -n > numbered.txt')
1968 use Fcntl qw(:DEFAULT :flock);
737 or die "Couldn't open a pipe into cat: $!";
1969 open(FH, "< filename") or die "can't open filename: $!";
1970 flock(FH, LOCK_SH) or die "can't lock filename: $!";
1971 # now read from FH
1972
1973=begin original
1974738
1975You can get a non-blocking lock by using C<LOCK_NB>.
739 for my $line (@processed) {
740 print $cat_fh $line;
1977=end original
741 }
1978
1979C<LOCK_NB> を使うことでブロックしないロックも得られます。
1980
1981 flock(FH, LOCK_SH | LOCK_NB)
1982 or die "can't lock filename: $!";
1983
1984=begin original
1985
1986This can be useful for producing more user-friendly behaviour by warning
1987if you're going to be blocking:
1988
1989=end original
1990
1991ブロックするときに警告することで、よりユーザーにやさしい振る舞いを
1992することは有用です:
1993
1994 use 5.004;
1995 use Fcntl qw(:DEFAULT :flock);
1996 open(FH, "< filename") or die "can't open filename: $!";
1997 unless (flock(FH, LOCK_SH | LOCK_NB)) {
1998 $| = 1;
1999 print "Waiting for lock...";
2000 flock(FH, LOCK_SH) or die "can't lock filename: $!";
2001 print "got it.\n"
2002 }
2003 # now read from FH
2004742
2005743=begin original
2006744
2007To get an exclusive lock, typically used for writing, you have to be
745Here, we use a second C<open> argument of C<"|-">, signifying that the
2008careful. We C<sysopen> the file so it can be locked before it gets
746filehandle assigned to C<$cat_fh> should be a write-pipe. We can then
2009emptied. You can get a nonblocking version using C<LOCK_EX | LOCK_NB>.
747use it just as we would a write-only ordinary filehandle, including the
748basic function of C<print>-ing data to it.
2010749
2011750=end original
2012751
2013(典型的には書き込みため) 排他ロック得るためには、慎重になる
752ここで、C<open> 2 番目の引数C<"|-"> 使います;
2014必要があます。
753これによ、C<$cat_fh> に代入されるファイルハンドルが書き込み
2015空なる前にロックするために、ファルを C<sysopen> 開きます。
754あることを示します。
2016C<LOCK_EX | LOCK_NB> を使った非ブロック版も得られま
755それから、データを C<print> する基本的な関数を含めて、
756書き込み専用の普通のファイルハンドルを使うのと同じようにこれを使えます。
2018 use 5.004;
2019 use Fcntl qw(:DEFAULT :flock);
2020 sysopen(FH, "filename", O_WRONLY | O_CREAT)
2021 or die "can't open filename: $!";
2022 flock(FH, LOCK_EX)
2023 or die "can't lock filename: $!";
2024 truncate(FH, 0)
2025 or die "can't truncate filename: $!";
2026 # now write to FH
2027757
2028758=begin original
2029759
2030Finally, due to the uncounted millions who cannot be dissuaded from
760Note that the third argument, specifying the command that we wish to
2031wasting cycles on useless vanity devices called hit counters, here's
761pipe to, sets up C<cat> to redirect its output via that C<< ">" >>
2032how to increment a number in a file safely:
762symbol into the file C<numbered.txt>. This can start to look a little
763tricky, because that same symbol would have meant something
764entirely different had it showed it in the second argument to C<open>!
765But here in the third argument, it's simply part of the shell command that
766Perl will open the pipe into, and Perl itself doesn't invest any special
767meaning to it.
2033768
2034769=end original
2035770
2036最後に、アクセスカウタと呼ばれ無駄で空虚な装置のために CPU パワーを
771パイプしたいコマドを指定す3 番目の引数は、
2037無駄遣いすることから逃れられない無慮数百万ため
772C<cat> 出力を C<< ">" >> 記号を使ってファイル C<numbered.txt>
2038あるファルの数値を安全増加させ方法を以下ます:
773リダレクトするよう指定していこと注意てください。
774これは最初は少しおかしく見えるかもしれません;
2040 use Fcntl qw(:DEFAULT :flock);
775この同じ記号は、C<open> 2 番目の引数では全く違うものを意味するからです!
776しかし、ここ 3 番目の引数では、これは単に Perl がパイプを開く
2042 sysopen(FH, "numfile", O_RDWR | O_CREAT)
777シェルコマンドの一部であり、Perl 自身はこれに何の特別な意味も与えません。
2043 or die "can't open numfile: $!";
2044 # autoflush FH
2045 $ofh = select(FH); $| = 1; select ($ofh);
2046 flock(FH, LOCK_EX)
2047 or die "can't write-lock numfile: $!";
2048
2049 $num = <FH> || 0;
2050 seek(FH, 0, 0)
2051 or die "can't rewind numfile : $!";
2052 print FH $num+1, "\n"
2053 or die "can't write numfile: $!";
2054
2055 truncate(FH, tell(FH))
2056 or die "can't truncate numfile: $!";
2057 close(FH)
2058 or die "can't close numfile: $!";
2059778
2060=head2 IO Layers
779=head2 Expressing the command as a list
2061780
2062(IO 層)
781(コマンドをリストとして表現する)
2063782
2064783=begin original
2065784
2066In Perl 5.8.0 a new I/O framework called "PerlIO" was introduced.
785For opening pipes, Perl offers the option to call C<open> with a list
2067This is a new "plumbing" for all the I/O happening in Perl; for the
786comprising the desired command and all its own arguments as separate
2068most part everything will work just as it did, but PerlIO also brought
787elements, rather than combining them into a single string as in the
2069in some new features such as the ability to think of I/O as "layers".
788examples above. For instance, we could have phrased the C<open> call in
2070One I/O layer may in addition to just moving the data also do
789the first example like this:
2071transformations on the data. Such transformations may include
2072compression and decompression, encryption and decryption, and transforming
2073between various character encodings.
2074790
2075791=end original
2076792
2077Perl 5.8.0 で"PerlIO"呼ばる新しい I/O フレームワークが
793パイプを開くために、Perl は、目的のコマンド自身の引数を、
2078導入されまた。
794前述の例のように単一の文字列とて結合するのではなく、
2079 Perl で発生る全ての I/O のための新し「配管」です;
795別個の要素として構成さたリストで C<open> を呼び出
2080ほとんど全の部分では単に今で通りに動作しまが、
796選択肢を提供します
2081I/O を「層」として考るため機能のような、新しい要素も導入されています
797ば、最初 C<open> 呼び出しは次のように書けます:
2082ある I/O 層は単にデータを移動させるだけでなく、データを変換するかも知れません。
2083このような変換には、圧縮と展開、暗号化と復号化、様々な文字エンコーディング間の
2084変換を含むかも知れません。
2085798
2086=begin original
799 open(my $sort_fh, '-|', 'sort', '-u', glob('unsorted/*.txt'))
800 or die "Couldn't open a pipe into sort: $!";
2088Full discussion about the features of PerlIO is out of scope for this
2089tutorial, but here is how to recognize the layers being used:
2090
2091=end original
2092
2093PerlIO の機能に関する完全な議論はこのチュートリアルの対象外ですが、
2094層が使われていることをどうやって認識するかを以下に示します:
2095
2096=over 4
2097
2098=item *
2099801
2100802=begin original
2101803
2102The three-(or more)-argument form of C<open> is being used and the
804When you call C<open> this way, Perl invokes the given command directly,
2103second argument contains something else in addition to the usual
805bypassing the shell. As such, the shell won't try to interpret any
2104C<< '<' >>, C<< '>' >>, C<< '>>' >>, C<< '|' >> and their variants,
806special characters within the command's argument list, which might
2105for example:
807overwise have unwanted effects. This can make for safer, less
808error-prone C<open> calls, useful in cases such as passing in variables
809as arguments, or even just referring to filenames with spaces in them.
2106810
2107811=end original
2108812
21093 (以上) 引数形式の C<open> が使われ2 番目の引数に通常の
813方法で C<open> を呼び出す場合
2110C<< '<' >>, C<< '>' >>, C<< '>>' >>, C<< '|' >> およびそのバリエー
814Perl ェルをバイパスして指定されたコマドを直接起動します。
2111以外何かが含れている場合; 例えば:
815シェルはコマンド路引数リストの中の特殊文字を解釈しようとはしせん;
816さもなければ望まない効果を生むことがあります。
2113 open(my $fh, "<:crlf", $fn);
817これはより安全で、C<open> 呼び出しの誤りを減らし、
818引数として変数の内容を渡すような場合に有用で、
2115=item *
819単に空白を含むファイルを参照する場合にも安全です。
2116820
2117821=begin original
2118822
2119The two-argument form of C<binmode> is being used, for example
823However, when you I<do> want to pass a meaningful metacharacter to the
824shell, such with the C<"*"> inside that final C<unsorted/*.txt> argument
825here, you can't use this alternate syntax. In this case, we have worked
826around it via Perl's handy C<glob> built-in function, which evaluates
827its argument into a list of filenames ? and we can safely pass that
828resulting list right into C<open>, as shown above.
2120829
2121830=end original
2122831
21232 引数形式C<binmode> が使われてる場合; 例えば
832しかし、シェルに意味あるメタ文字を I<渡した>、
833例えば最終的な C<unsorted/*.txt> の中の C<"*"> のような場合、
2125 binmode($fh, ":encoding(utf16)");
834この代替文法は使えません。
835この場合、引数をファイル名として評価する Perl の便利な C<glob> 組み込み関数で
2127=back
836回避します; そして前述したように、結果のリストを C<open> に安全に
837渡せます。
2128838
2129839=begin original
2130840
2131For more detailed discussion about PerlIO see L<PerlIO>;
841Note also that representing piped-command arguments in list form like
2132for more detailed discussion about Unicode and I/O see L<perluniintro>.
842this doesn't work on every platform. It will work on any Unix-based OS
843that provides a real C<fork> function (e.g. macOS or Linux), as well as
844on Windows when running Perl 5.22 or later.
2133845
2134846=end original
2135847
2136PerlIO に関するり詳細議論について L<PerlIO> を参照しください;
848また、このリスト形式でのパイプコマンド引数表現、全
2137Unicode と I/O に関するより詳細議論については L<perluniintro> を
849プラットフォームで動作するわけではないことに注意しください。
2138参照してください。
850真の C<fork> 関数を提供する Unix ベースの OS (例えば macOS や Linux)、
851および Perl 5.22 以降の Windows では動作します。
2139852
2140=head1 SEE ALSO
853=head1 SEE ALSO
2141854
2142855=begin original
2143856
2144The C<open> and C<sysopen> functions in perlfunc(1);
857The full documentation for L<C<open>|perlfunc/open FILEHANDLE,MODE,EXPR>
2145the system open(2), dup(2), fopen(3), and fdopen(3) manpages;
858provides a thorough reference to this function, beyond the best-practice
2146the POSIX documentation.
859basics covered here.
2147860
2148861=end original
2149862
2150perlfunc(1) の C<open> 及び C<sysopen> 関数;
863L<C<open>|perlfunc/open FILEHANDLE,MODE,EXPR> の完全な文書は、
2151ステ open(2), dup(2), fopen(3), fdopen(3) man ページ;
864ここでカバーしているベトプラクィスベースを超えて、
2152POSIX 文書
865この関数の完全なリファレンスを提供します
2153866
2154867=head1 AUTHOR and COPYRIGHT
2155868
2156Copyright 1998 Tom Christiansen.
869Copyright 2013 Tom Christiansen; now maintained by Perl5 Porters
2157
2158This documentation is free; you can redistribute it and/or modify it
2159under the same terms as Perl itself.
2160
2161Irrespective of its distribution, all code examples in these files are
2162hereby placed into the public domain. You are permitted and
2163encouraged to use this code in your own programs for fun or for profit
2164as you see fit. A simple comment in the code giving credit would be
2165courteous but is not required.
2166
2167=head1 HISTORY
2168870
2169First release: Sat Jan 9 08:09:11 MST 1999
871This documentation is free; you can redistribute it and/or modify it under
872the same terms as Perl itself.
2170873
2171874=begin meta
2172875
2173Translate: SHIRAKATA Kentaro <argrath@ub32.org>
876Translate: SHIRAKTA Kentaro <argrath@ub32.org>
2174877Status: completed
2175878
2176879=end meta