perl-5.38.0
open FILEHANDLE,MODE,EXPR
open FILEHANDLE,MODE,EXPR,LIST
open FILEHANDLE,MODE,REFERENCE
open FILEHANDLE,EXPR
open FILEHANDLE

Associates an internal FILEHANDLE with the external file specified by EXPR. That filehandle will subsequently allow you to perform I/O operations on that file, such as reading from it or writing to it.

内部の FILEHANDLE を、EXPR で指定された外部ファイルに関連付けます。 このファイルハンドルはその後、読んだり書いたりといったそのファイルへの I/O 操作をできるようにします。

Instead of a filename, you may specify an external command (plus an optional argument list) or a scalar reference, in order to open filehandles on commands or in-memory scalars, respectively.

ファイル名の代わりに、コマンドやメモリ内スカラへのファイルハンドルを 開くために、外部コマンド (とオプションの引数リスト) やスカラリファレンスを 指定できます。

A thorough reference to open follows. For a gentler introduction to the basics of open, see also the perlopentut manual page.

open の完全なリファレンスは後述します。 open の基本に関するより親切な導入に関しては、 perlopentut man ページも参照してください。

Working with files

Most often, open gets invoked with three arguments: the required FILEHANDLE (usually an empty scalar variable), followed by MODE (usually a literal describing the I/O mode the filehandle will use), and then the filename that the new filehandle will refer to.

ほとんどの場合、open は 3 引数で起動されます: 必須の FILEHANDLE (通常は空のスカラ変数), 引き続いて MODE (通常は ファイルハンドルを使う I/O モードを記述するリテラル)、 それから新しいファイルハンドルが参照するファイル名です。

Simple examples

(単純な例)

Reading from a file:

ファイルからの読み込み:

    open(my $fh, "<", "input.txt")
        or die "Can't open < input.txt: $!";

    # Process every line in input.txt
    while (my $line = readline($fh)) {
        #
        # ... do something interesting with $line here ...
        #
    }

or writing to one:

そして書き込み:

    open(my $fh, ">", "output.txt")
        or die "Can't open > output.txt: $!";

    print $fh "This line gets printed into output.txt.\n";

For a summary of common filehandle operations such as these, see "Files and I/O" in perlintro.

このような基本的なファイルハンドル操作の要約については、 "Files and I/O" in perlintro を参照してください。

About filehandles

(ファイルハンドルについて)

The first argument to open, labeled FILEHANDLE in this reference, is usually a scalar variable. (Exceptions exist, described in "Other considerations", below.) If the call to open succeeds, then the expression provided as FILEHANDLE will get assigned an open filehandle. That filehandle provides an internal reference to the specified external file, conveniently stored in a Perl variable, and ready for I/O operations such as reading and writing.

このリファレンスでは FILEHANDLE というラベルが付いている、 open の最初の引数は、通常はスカラ変数です。 (例外があります; 後述する "Other considerations" で記述されます。) open の呼び出しが成功すると、 FILEHANDLE として提供された式には、 開いた ファイルハンドル が代入されます。 このファイルハンドルは指定された外部ファイルへの内部参照を提供し、 好都合なように Perl 変数に保管し、読み書きのような I/O 操作の準備をします。

About modes

(モードについて)

When calling open with three or more arguments, the second argument -- labeled MODE here -- defines the open mode. MODE is usually a literal string comprising special characters that define the intended I/O role of the filehandle being created: whether it's read-only, or read-and-write, and so on.

3 引数以上で open を呼び出すとき、 2 番目の引数 -- ここでは MODE -- は 開くモード を定義します。 MODE は普通、作られるファイルハンドルが意図している I/O の役割 (読み込み専用、 読み書き、など)を定義する特別な文字で構成されるリテラルな文字列です。

If MODE is <, the file is opened for input (read-only). If MODE is >, the file is opened for output, with existing files first being truncated ("clobbered") and nonexisting files newly created. If MODE is >>, the file is opened for appending, again being created if necessary.

MODE が < の場合、ファイルは入力用(読み込み専用)に開かれます。 MODE が > の場合、ファイルは出力用に開かれ、既にファイルが ある場合は切り詰められ(上書きされ)、ない場合は新しく作られます。 MODE が >> の場合、ファイルは追加用に開かれ、やはり必要なら 作成されます。

You can put a + in front of the > or < to indicate that you want both read and write access to the file; thus +< is almost always preferred for read/write updates--the +> mode would clobber the file first. You can't usually use either read-write mode for updating textfiles, since they have variable-length records. See the -i switch in perlrun for a better approach. The file is created with permissions of 0666 modified by the process's umask value.

ファイルに読み込みアクセスと書き込みアクセスの両方をしたいことを示すために、 >< の前に + を付けることができます: 従って、ほとんど常に +< が読み書き更新のために使われます -- +> モードはまずファイルを上書きします。 普通はこれらの読み書きモードをテキストファイルの更新のためには使えません; なぜなら可変長のレコードで構成されているからです。 よりよい手法については perlrun-i オプションを参照してください。 ファイルは 0666 をプロセスの umask 値で修正した パーミッションで作成されます。

These various prefixes correspond to the fopen(3) modes of r, r+, w, w+, a, and a+.

これらの様々な前置詞は fopen(3)r, r+, w, w+, a, a+ のモードに対応します。

More examples of different modes in action:

実用的な異なったモードに関する更なる例:

 # Open a file for concatenation
 open(my $log, ">>", "/usr/spool/news/twitlog")
     or warn "Couldn't open log file; discarding input";

 # Open a file for reading and writing
 open(my $dbase, "+<", "dbase.mine")
     or die "Can't open 'dbase.mine' for update: $!";
Checking the return value

(返り値をチェックする)

Open returns nonzero on success, the undefined value otherwise. If the open involved a pipe, the return value happens to be the pid of the subprocess.

open は、成功時にはゼロ以外を返し、失敗時には未定義値を返します。 パイプに関る open のときには、返り値は サブプロセスの pid となります。

When opening a file, it's seldom a good idea to continue if the request failed, so open is frequently used with die. Even if you want your code to do something other than die on a failed open, you should still always check the return value from opening a file.

ファイルを開く時、開くのに失敗した時に通常の処理を続けるのは普通は悪い 考えなので、open はしばしば die と結び付けられて使われます。 開くときに失敗したときに die 意外の何かを したい場合でも、ファイルを開いた時の返り値を常にチェックするべきです。

Specifying I/O layers in MODE

(MODE で I/O 層を指定する)

You can use the three-argument form of open to specify I/O layers (sometimes referred to as "disciplines") to apply to the new filehandle. These affect how the input and output are processed (see open and PerlIO for more details). For example:

新しいファイルハンドルに適用する I/O 層(「ディシプリン」とも呼ばれます)を指定するために open の 3 引数形式を使えます。 これらはどのように入出力が処理されるかに影響を与えます (詳細については openPerlIO を参照してください)。 例えば:

    # loads PerlIO::encoding automatically
    open(my $fh, "<:encoding(UTF-8)", $filename)
        || die "Can't open UTF-8 encoded $filename: $!";

This opens the UTF8-encoded file containing Unicode characters; see perluniintro. Note that if layers are specified in the three-argument form, then default layers stored in ${^OPEN} (usually set by the open pragma or the switch -CioD) are ignored. Those layers will also be ignored if you specify a colon with no name following it. In that case the default layer for the operating system (:raw on Unix, :crlf on Windows) is used.

これは、Unicode 文字を含む UTF8 エンコードされたファイルを開きます; perluniintro を参照してください。 3 引数形式で層を指定すると、${^OPEN} (通常は open プラグマか -CioD オプションでセットされます) に 保存されたデフォルト層は無視されることに注意してください。 これらの層は、名前なしでコロンを指定した場合にも無視されます。 この場合 OS のデフォルトの層 (Unix では :raw、Windows では :crlf) が 使われます。

On some systems (in general, DOS- and Windows-based systems) binmode is necessary when you're not working with a text file. For the sake of portability it is a good idea always to use it when appropriate, and never to use it when it isn't appropriate. Also, people can set their I/O to be by default UTF8-encoded Unicode, not bytes.

テキストファイルでないものを扱う場合に binmode が必要な システムもあります(一般的には DOS と Windows ベースのシステムです)。 移植性のために、適切なときには常にこれを使い、適切でないときには 決して使わないというのは良い考えです。 また、デフォルトとして I/O を bytes ではなく UTF-8 エンコードされた Unicode にセットすることも出来ます。

Using undef for temporary files

(一時ファイルとして undef を使う)

As a special case the three-argument form with a read/write mode and the third argument being undef:

特別な場合として、3 引数の形で読み書きモードで 3 番目の引数が undef の場合:

    open(my $tmp, "+>", undef) or die ...

opens a filehandle to a newly created empty anonymous temporary file. (This happens under any mode, which makes +> the only useful and sensible mode to use.) You will need to seek to do the reading.

新しく作成した空の無名一時ファイルとしてファイルハンドルを開きます。 (これはどのモードでも起こりますが、+> のみが有用で意味があります。) 読み込みを行うためには seek が 必要です。

Opening a filehandle into an in-memory scalar

(ファイルハンドルをメモリ内スカラに開く)

You can open filehandles directly to Perl scalars instead of a file or other resource external to the program. To do so, provide a reference to that scalar as the third argument to open, like so:

ファイルやその他のプログラムから見ての外部リソースではなく、 Perl スカラに対して直接ファイルハンドルを開くことができます。 そうするためには、次のように、open の 3 番目の引数としてその スカラへのリファレンスを提供します:

 open(my $memory, ">", \$var)
     or die "Can't open memory file: $!";
 print $memory "foo!\n";    # output will appear in $var

To (re)open STDOUT or STDERR as an in-memory file, close it first:

STDOUTSTDERR を「オンメモリの」ファイルとして 再び開きたい場合は、先にそれを閉じます:

    close STDOUT;
    open(STDOUT, ">", \$variable)
        or die "Can't open STDOUT: $!";

The scalars for in-memory files are treated as octet strings: unless the file is being opened with truncation the scalar may not contain any code points over 0xFF.

オンメモリファイルのためのスカラはオクテット文字列として扱われます: ファイルが切り詰められて開かれない限り、 スカラは 0xFF を超える符号位置を含みません。

Opening in-memory files can fail for a variety of reasons. As with any other open, check the return value for success.

オンメモリファイルを開くのは様々な理由で失敗する ことがあります。 その他の open と同様、成功したかを返り値でチェックしてください。

Technical note: This feature works only when Perl is built with PerlIO -- the default, except with older (pre-5.16) Perl installations that were configured to not include it (e.g. via Configure -Uuseperlio). You can see whether your Perl was built with PerlIO by running perl -V:useperlio. If it says 'define', you have PerlIO; otherwise you don't.

技術ノート: この機能は Perl が PerlIO を使ってビルドされている 場合にのみ動作します; これは (Configure -Uuseperlio によって) これを含まないように設定されていた古い (5.16 より前の) Perl でない限り、 デフォルトです。 Perl が PerlIO つきでビルドされているかどうかを確認するには、 perl -V:useperlio を見ます。 これが 'define' なら PerlIO を使っています; そうでなければ使っていません。

See perliol for detailed info on PerlIO.

PerlIO に関する詳しい情報については perliol を参照してください。

Opening a filehandle into a command

(ファイルハンドルをコマンドに開く)

If MODE is |-, then the filename is interpreted as a command to which output is to be piped, and if MODE is -|, the filename is interpreted as a command that pipes output to us. In the two-argument (and one-argument) form, one should replace dash (-) with the command. See "Using open() for IPC" in perlipc for more examples of this. (You are not allowed to open to a command that pipes both in and out, but see IPC::Open2, IPC::Open3, and "Bidirectional Communication with Another Process" in perlipc for alternatives.)

MODE が |- の場合、ファイル名は出力がパイプされるコマンドとして 解釈され、MODE が -| の場合、ファイル名は出力がこちらに パイプされるコマンドとして解釈されます。 2 引数(と 1 引数) の形式ではハイフン(-)をコマンドの代わりに使えます。 これに関するさらなる例については "Using open() for IPC" in perlipc を 参照してください。 (open を入出力 両用 にパイプすることは 出来ませんが、代替案としては IPC::Open2, IPC::Open3, "Bidirectional Communication with Another Process" in perlipc を 参照してください。)

 open(my $article_fh, "-|", "caesar <$article")  # decrypt
                                                 # article
     or die "Can't start caesar: $!";

 open(my $article_fh, "caesar <$article |")      # ditto
     or die "Can't start caesar: $!";

 open(my $out_fh, "|-", "sort >Tmp$$")    # $$ is our process id
     or die "Can't start sort: $!";

In the form of pipe opens taking three or more arguments, if LIST is specified (extra arguments after the command name) then LIST becomes arguments to the command invoked if the platform supports it. The meaning of open with more than three arguments for non-pipe modes is not yet defined, but experimental "layers" may give extra LIST arguments meaning.

パイプでの三つ以上の引数の形式では、LIST (コマンド名の後の追加の引数) が 指定されると、プラットフォームが対応していれば、LIST は起動される コマンドへの引数となります。 パイプモードではない open での 三つ以上の引数の意味はまだ未定義ですが、実験的な「層」は 追加の LIST 引数の意味を与えます。

If you open a pipe on the command - (that is, specify either |- or -| with the one- or two-argument forms of open), an implicit fork is done, so open returns twice: in the parent process it returns the pid of the child process, and in the child process it returns (a defined) 0. Use defined($pid) or // to determine whether the open was successful.

1 引数 または 2 引数の形の open) で (-||- というふうに) - というコマンドにパイプを開くと、 暗黙の fork が行なわれるので、 open は 2 回返ります; 親プロセスには子プロセスの pid が返され、子プロセスには (定義された) 0 が 返されます。 open が成功したかどうかを調べるには、defined($pid) または // を 使います。

For example, use either

例えば、以下の二つ

   my $child_pid = open(my $from_kid, "-|")
        // die "Can't fork: $!";

or

または

   my $child_pid = open(my $to_kid,   "|-")
        // die "Can't fork: $!";

followed by

を使って、後で以下のようにします。

    if ($child_pid) {
        # am the parent:
        # either write $to_kid or else read $from_kid
        ...
       waitpid $child_pid, 0;
    } else {
        # am the child; use STDIN/STDOUT normally
        ...
        exit;
    }

The filehandle behaves normally for the parent, but I/O to that filehandle is piped from/to the STDOUT/STDIN of the child process. In the child process, the filehandle isn't opened--I/O happens from/to the new STDOUT/STDIN. Typically this is used like the normal piped open when you want to exercise more control over just how the pipe command gets executed, such as when running setuid and you don't want to have to scan shell commands for metacharacters.

親プロセスでは、このファイルハンドルは通常通りに動作しますが、行なわれる 入出力は、子プロセスの STDIN/STDOUT にパイプされます。 子プロセス側では、そのファイルハンドルは開かれず、入出力は新しい STDOUT か STDIN に対して行なわれます。 これは、setuid で実行して、シェルコマンドのメタ文字を 検索させたくないような場合に、パイプコマンドの起動の仕方を 制御したいとき、普通のパイプの open と同じように使います。

The following blocks are more or less equivalent:

以下の組み合わせは、だいたい同じものです:

    open(my $fh, "|tr '[a-z]' '[A-Z]'");
    open(my $fh, "|-", "tr '[a-z]' '[A-Z]'");
    open(my $fh, "|-") || exec 'tr', '[a-z]', '[A-Z]';
    open(my $fh, "|-", "tr", '[a-z]', '[A-Z]');

    open(my $fh, "cat -n '$file'|");
    open(my $fh, "-|", "cat -n '$file'");
    open(my $fh, "-|") || exec "cat", "-n", $file;
    open(my $fh, "-|", "cat", "-n", $file);

The last two examples in each block show the pipe as "list form", which is not yet supported on all platforms. (If your platform has a real fork, such as Linux and macOS, you can use the list form; it also works on Windows with Perl 5.22 or later.) You would want to use the list form of the pipe so you can pass literal arguments to the command without risk of the shell interpreting any shell metacharacters in them. However, this also bars you from opening pipes to commands that intentionally contain shell metacharacters, such as:

それぞれのブロックの末尾二つの例ではパイプを「リスト形式」にしていますが、 これはまだ全てのプラットフォームで対応しているわけではなりません。 (もし実行しているプラットフォームで本当の fork があれば(Linux や MacOS X なら)リスト形式が使えます; Perl 5.22 以降では Windows でも 動作します。) パイプのリスト形式を使うことで、コマンドへのリテラルな引数を、 シェルのメタ文字をシェルが解釈するリスクなしに渡すことができます。 しかし、これは以下のように意図的にシェルメタ文字を含むコマンドをパイプとして 開くことを妨げます:

    open(my $fh, "|cat -n | expand -4 | lpr")
        || die "Can't open pipeline to lpr: $!";

See "Safe Pipe Opens" in perlipc for more examples of this.

これに関する更なる例については "Safe Pipe Opens" in perlipc を 参照してください。

Duping filehandles

(ハンドルの複製)

You may also, in the Bourne shell tradition, specify an EXPR beginning with >&, in which case the rest of the string is interpreted as the name of a filehandle (or file descriptor, if numeric) to be duped (as in dup(2)) and opened. You may use & after >, >>, <, +>, +>>, and +<. The mode you specify should match the mode of the original filehandle. (Duping a filehandle does not take into account any existing contents of IO buffers.) If you use the three-argument form, then you can pass either a number, the name of a filehandle, or the normal "reference to a glob".

Bourne シェルの慣例にしたがって、EXPR の先頭に >& を付けると、EXPR の残りの文字列をファイルハンドル名 (数字であれば、ファイル記述子) と解釈して、それを (dup(2) によって) 複製してオープンします。 & は、>, >>, <, +>, +>>, +<というモード指定に付けることができます。 指定するモード指定は、もとのファイルハンドルのモードと 合っていないといけません。 (ファイルハンドルの複製は既に存在する IO バッファの内容に含めません。) 3 引数形式を使う場合は、数値を渡すか、ファイルハンドルの名前を渡すか、 通常の「グロブへのリファレンス」を渡します。

Here is a script that saves, redirects, and restores STDOUT and STDERR using various methods:

STDOUTSTDERR 保存し、リダイレクトし、元に戻すスクリプトを示します:

    #!/usr/bin/perl
    open(my $oldout, ">&STDOUT")
        or die "Can't dup STDOUT: $!";
    open(OLDERR,     ">&", \*STDERR)
        or die "Can't dup STDERR: $!";

    open(STDOUT, '>', "foo.out")
        or die "Can't redirect STDOUT: $!";
    open(STDERR, ">&STDOUT")
        or die "Can't dup STDOUT: $!";

    select STDERR; $| = 1;  # make unbuffered
    select STDOUT; $| = 1;  # make unbuffered

    print STDOUT "stdout 1\n";  # this works for
    print STDERR "stderr 1\n";  # subprocesses too

    open(STDOUT, ">&", $oldout)
        or die "Can't dup \$oldout: $!";
    open(STDERR, ">&OLDERR")
        or die "Can't dup OLDERR: $!";

    print STDOUT "stdout 2\n";
    print STDERR "stderr 2\n";

If you specify '<&=X', where X is a file descriptor number or a filehandle, then Perl will do an equivalent of C's fdopen(3) of that file descriptor (and not call dup(2)); this is more parsimonious of file descriptors. For example:

X をファイル記述子の番号かファイルハンドルとして、 '<&=X' と指定すると、Perl はそのファイル記述子に対する C の fdopen(3) と同じことを行ないます(そして dup(2) は呼び出しません); これはファイル記述子をより節約します。 例えば:

    # open for input, reusing the fileno of $fd
    open(my $fh, "<&=", $fd)

or

または

    open(my $fh, "<&=$fd")

or

または

    # open for append, using the fileno of $oldfh
    open(my $fh, ">>&=", $oldfh)

Being parsimonious on filehandles is also useful (besides being parsimonious) for example when something is dependent on file descriptors, like for example locking using flock. If you do just open(my $A, ">>&", $B), the filehandle $A will not have the same file descriptor as $B, and therefore flock($A) will not flock($B) nor vice versa. But with open(my $A, ">>&=", $B), the filehandles will share the same underlying system file descriptor.

ファイルハンドルを倹約することは、(倹約できること以外に)何かが ファイル記述子に依存している場合、例えば flock を使った ファイルロックといった場合に有用です。 open(my $A, ">>&", $B) とすると、ファイルハンドル $A$B と同じ ファイル記述子にはならないので、flock($A)flock($B) は別々になります。 しかし open(my $A, ">>&=", $B) ではファイルハンドルは基礎となるシステムの 同じファイル記述子を共有します。

Note that under Perls older than 5.8.0, Perl uses the standard C library's' fdopen(3) to implement the = functionality. On many Unix systems, fdopen(3) fails when file descriptors exceed a certain value, typically 255. For Perls 5.8.0 and later, PerlIO is (most often) the default.

5.8.0 より前の Perl の場合、= 機能の実装は 標準 C ライブラリの fdopen(3) を使っています。 多くの Unix システムでは、fdopen(3) はファイル記述子がある値 (典型的には 255)を超えた場合に失敗することが知られています。 5.8.0 以降の Perl では、(ほぼ確実に) PerlIO がデフォルトです。

Legacy usage

(古い使い方)

This section describes ways to call open outside of best practices; you may encounter these uses in older code. Perl does not consider their use deprecated, exactly, but neither is it recommended in new code, for the sake of clarity and readability.

この節では、ベストプラクティスではない open の呼び出し方について 記述します; より古いコードでこれらが使われているのに遭遇するかもしれません。 厳密には、Perl はこれらの仕様を廃止予定にはしていませんが、 明瞭性と可読性のために、新しいコードには薦めません。

Specifying mode and filename as a single argument

(モードとファイル名を一つの引数で指定する)

In the one- and two-argument forms of the call, the mode and filename should be concatenated (in that order), preferably separated by white space. You can--but shouldn't--omit the mode in these forms when that mode is <. It is safe to use the two-argument form of open if the filename argument is a known literal.

1 引数 と 2 引数の形式ではモードとファイル名は(この順番で) 結合されます(空白によって分割されているかもしれません)。 この形式で、モードが '<' の場合はモードを省略できます (が、 するべきではありません)。 ファイル引数が既知のリテラルの場合、2 引数形式の open は安全です。

 open(my $dbase, "+<dbase.mine")          # ditto
     or die "Can't open 'dbase.mine' for update: $!";

In the two-argument (and one-argument) form, opening <- or - opens STDIN and opening >- opens STDOUT.

2 引数(と 1 引数)で <-- を open すると STDIN が オープンされ、>- を open すると STDOUT がオープンされます。

New code should favor the three-argument form of open over this older form. Declaring the mode and the filename as two distinct arguments avoids any confusion between the two.

新しいコードでは、このより古い形式ではなく、3 引数形式の open を 使うべきです。 モードとファイル名を異なった二つの引数として指定することで、 二つの間の混乱を避けられます。

Calling open with one argument via global variables

(グローバル変数を使って open を 1 引数で呼び出す)

As a shortcut, a one-argument call takes the filename from the global scalar variable of the same name as the filehandle:

短縮版として、1 引数呼び出しでは、ファイル名を、ファイルハンドルと同じ名前の グローバルなスカラ変数から取ります:

    $ARTICLE = 100;
    open(ARTICLE)
        or die "Can't find article $ARTICLE: $!\n";

Here $ARTICLE must be a global (package) scalar variable - not one declared with my or state.

ここで $ARTICLE はグローバル(パッケージ)スカラ変数でなければなりません - mystate で宣言された 変数ではありません。

Assigning a filehandle to a bareword

(ファイルハンドルを裸の単語に代入する)

An older style is to use a bareword as the filehandle, as

より古いスタイルは、次のように、ファイルハンドルとして裸の単語を使います

    open(FH, "<", "input.txt")
       or die "Can't open < input.txt: $!";

Then you can use FH as the filehandle, in close FH and <FH> and so on. Note that it's a global variable, so this form is not recommended when dealing with filehandles other than Perl's built-in ones (e.g. STDOUT and STDIN). In fact, using a bareword for the filehandle is an error when the bareword_filehandles feature has been disabled. This feature is disabled by default when in the scope of use v5.36.0 or later.

それから FH を、close FH<FH> などのように、 ファイルハンドルとして使えます。 これはグローバル変数なので、Perl の組み込みのもの (例えば STDOUT と STDIN) 以外では非推奨であることに注意してください。 実際、bareword_filehandles 機能が無効になっている場合は ファイルハンドルに裸の単語を使うことはエラーです。 この機能は、use v5.36.0 以降のスコープ内ではデフォルトでは 無効になっています。

Other considerations

(その他の考慮点)

Automatic filehandle closure

(自動的にファイルハンドルを閉じる)

The filehandle will be closed when its reference count reaches zero. If it is a lexically scoped variable declared with my, that usually means the end of the enclosing scope. However, this automatic close does not check for errors, so it is better to explicitly close filehandles, especially those used for writing:

ファイルハンドルは、参照カウントが 0 になったときに閉じられます。 これが my で宣言されたレキシカルスコープを持つ変数の場合、 普通は囲まれたスコープの終わりを意味します。 しかし、この自動閉じはエラーをチェックしないので、特に書き込み用の場合は、 明示的にファイルハンドルを閉じる方がよいです。

    close($handle)
       || warn "close failed: $!";
Automatic pipe flushing

(パイプの自動フラッシュ)

Perl will attempt to flush all files opened for output before any operation that may do a fork, but this may not be supported on some platforms (see perlport). To be safe, you may need to set $| ($AUTOFLUSH in English) or call the autoflush method of IO::Handle on any open handles.

Perl は書き込み用に開いている全てのファイルに対して fork を行う前にフラッシュしようとしますが、これに対応していない プラットフォームもあります(perlport を参照してください)。 安全のために、$| (English モジュールでは $AUTOFLUSH) をセットするか、全ての開いているハンドルに対して IO::Handleautoflush メソッドを 呼び出す必要があるかもしれません。

On systems that support a close-on-exec flag on files, the flag will be set for the newly opened file descriptor as determined by the value of $^F. See "$^F" in perlvar.

ファイルに対する close-on-exec フラグをサポートしているシステムでは、 フラグは $^F の値で決定される、新しくオープンされた ファイル記述子に対してセットされます。 "$^F" in perlvar を参照してください。

Closing any piped filehandle causes the parent process to wait for the child to finish, then returns the status value in $? and ${^CHILD_ERROR_NATIVE}.

パイプのファイルハンドルを close することで、親プロセスは、子プロセスの終了を 待ち、それから $?${^CHILD_ERROR_NATIVE} にステータス値を 返します。

Direct versus by-reference assignment of filehandles

(ファイルハンドルの直接代入とリファレンスによる代入)

If FILEHANDLE -- the first argument in a call to open -- is an undefined scalar variable (or array or hash element), a new filehandle is autovivified, meaning that the variable is assigned a reference to a newly allocated anonymous filehandle. Otherwise if FILEHANDLE is an expression, its value is the real filehandle. (This is considered a symbolic reference, so use strict "refs" should not be in effect.)

FILEHANDLE (open を呼び出すときの最初の引数) が未定義のスカラ変数 (または配列かハッシュの要素)の場合、 新しいファイルハンドルが自動有効化され、その変数は新しく割り当てられた 無名ファイルハンドルへのリファレンスが代入されます。 さもなければ、もし FILEHANDLE が式なら、その値を求めている実際の ファイルハンドルの名前として使います。 (これはシンボリックリファレンスとして扱われるので、 use strict "refs" の影響を 受けません。)

Whitespace and special characters in the filename argument

(ファイル名引数の空白と特殊文字)

The filename passed to the one- and two-argument forms of open will have leading and trailing whitespace deleted and normal redirection characters honored. This property, known as "magic open", can often be used to good effect. A user could specify a filename of "rsh cat file |", or you could change certain filenames as needed:

1 引数 と 2 引数の形の open に渡された ファイル名は、はじめと終わりの空白が取り除かれ、通常のリダイレクト文字列を 受け付けます。 この機能は "magic open" として知られていますが、普通いい効果をもたらします。 ユーザーは "rsh cat file |" といったファイル名を指定できますし、 特定のファイル名を必要に応じて変更できます。

    $filename =~ s/(.*\.gz)\s*$/gzip -dc < $1|/;
    open(my $fh, $filename)
        or die "Can't open $filename: $!";

Use the three-argument form to open a file with arbitrary weird characters in it,

妙な文字が含まれているようなファイル名をオープンするには、 3 引数の形を使います。

    open(my $fh, "<", $file)
        || die "Can't open $file: $!";

otherwise it's necessary to protect any leading and trailing whitespace:

あるいは、次のようにして、最初と最後の空白を保護します:

    $file =~ s#^(\s)#./$1#;
    open(my $fh, "< $file\0")
        || die "Can't open $file: $!";

(this may not work on some bizarre filesystems). One should conscientiously choose between the magic and three-argument form of open:

(これは奇妙なファイルシステムでは動作しないかもしれません)。 openmagic3 引数 形式を誠実に 選択するべきです。

    open(my $in, $ARGV[0]) || die "Can't open $ARGV[0]: $!";

will allow the user to specify an argument of the form "rsh cat file |", but will not work on a filename that happens to have a trailing space, while

とするとユーザーは "rsh cat file |" という形の引数を指定できますが、 末尾にスペースがついてしまったファイル名では動作しません; 一方:

    open(my $in, "<", $ARGV[0])
        || die "Can't open $ARGV[0]: $!";

will have exactly the opposite restrictions. (However, some shells support the syntax perl your_program.pl <( rsh cat file ), which produces a filename that can be opened normally.)

はまったく逆の制限があります。 (しかし、一部のシェルは perl your_program.pl <( rsh cat file ) という 文法に対応していて、普通に開くことが出来るファイル名を出力します。)

Invoking C-style open

(C 形式の open の起動)

If you want a "real" C open(2), then you should use the sysopen function, which involves no such magic (but uses different filemodes than Perl open, which corresponds to C fopen(3)). This is another way to protect your filenames from interpretation. For example:

もし「本当の」C 言語の open(2) が必要なら、このような副作用のない sysopen 関数を使うべきです (ただし、C の fopen(3) に対応する Perl の open とは違うファイルモードを持ちます)。 これはファイル名を解釈から守るもう一つの方法です。 例えば:

    use IO::Handle;
    sysopen(my $fh, $path, O_RDWR|O_CREAT|O_EXCL)
        or die "Can't open $path: $!";
    $fh->autoflush(1);
    print $fh "stuff $$\n";
    seek($fh, 0, 0);
    print "File contains: ", readline($fh);

See seek for some details about mixing reading and writing.

読み書きを混ぜる場合の詳細については seek を参照してください。

Portability issues

(移植性の問題)

"open" in perlport を参照してください。