5.20.1

名前

perlopentut - simple recipes for opening files and pipes in Perl

perlopentut - Perl でファイルを開いたりパイプを使ったりするための簡単なレシピ

説明

Whenever you do I/O on a file in Perl, you do so through what in Perl is called a filehandle. A filehandle is an internal name for an external file. It is the job of the open function to make the association between the internal name and the external name, and it is the job of the close function to break that association.

Perl でファイルにタイして入出力をするとき、Perl では ファイルハンドル と 呼ばれるものを通して行います。 ファイルハンドルは外部ファイルに対する内部名です。 open 関数の仕事は内部名と外部名を関連づけることで、close 関数は 関連づけを壊すことです。

For your convenience, Perl sets up a few special filehandles that are already open when you run. These include STDIN, STDOUT, STDERR, and ARGV. Since those are pre-opened, you can use them right away without having to go to the trouble of opening them yourself:

便利なように、Perl は実行開始時に既に開いているいくつかの特別な ファイルハンドルを設定します。 それは STDIN, STDOUT, STDERR, ARGV です。 これらは既に開いているので、自分でこれらを開くときの問題を受けることなく 正しく使うことができます。

    print STDERR "This is a debugging message.\n";

    print STDOUT "Please enter something: ";
    $response = <STDIN> // die "how come no input?";
    print STDOUT "Thank you!\n";

    while (<ARGV>) { ... }

As you see from those examples, STDOUT and STDERR are output handles, and STDIN and ARGV are input handles. They are in all capital letters because they are reserved to Perl, much like the @ARGV array and the %ENV hash are. Their external associations were set up by your shell.

これらの例で見られるように、STDOUTSTDERR は出力ハンドルで、 STDINARGV は入力ハンドルです。 これらは @ARGV 配列や %ENV ハッシュと同様に Perl によって 予約されているので、全て大文字になっています。 これらの外部関連づけはシェルによって行われます。

You will need to open every other filehandle on your own. Although there are many variants, the most common way to call Perl's open() function is with three arguments and one return value:

その他のファイルハンドルは自分で開く必要があります。 多くのバリエーションはありますが、Perl の open() 関数を開く最も一般的な方法は 3 引数と一つの返り値のものです:

OK = open(HANDLE, MODE, PATHNAME)

OK = open(HANDLE, MODE, PATHNAME)

Where:

ここで:

OK

will be some defined value if the open succeeds, but undef if it fails;

これは、開くのに成功すれば何らかの定義された値、失敗すれば undef です;

HANDLE

should be an undefined scalar variable to be filled in by the open function if it succeeds;

これは、成功すれば open 巻数によって埋められる未定義のスカラ変数です;

MODE

is the access mode and the encoding format to open the file with;

これはファイルを開くときのアクセスモードとエンコーディング型式です;

PATHNAME

is the external name of the file you want opened.

これは開きたいファイルの外部名です。

Most of the complexity of the open function lies in the many possible values that the MODE parameter can take on.

open 関数の複雑さの大部分は、MODE 引数が多くの値を 取ることのできることにあります。

One last thing before we show you how to open files: opening files does not (usually) automatically lock them in Perl. See perlfaq5 for how to lock.

ファイルの開き方を説明する前に最後に一言: Perl ではファイルを開いても (普通は)自動的にロックすることはしません。 ロックの方法については perlfaq5 を参照してください。

テキストファイルを開く

読み込み用にテキストファイルを開く

If you want to read from a text file, first open it in read-only mode like this:

If you want to read from a text file, first open it in read-only mode like this: (TBT)

    my $filename = "/some/path/to/a/textfile/goes/here";
    my $encoding = ":encoding(UTF-8)";
    my $handle   = undef;     # this will be filled in on success

    open($handle, "< $encoding", $filename)
        || die "$0: can't open $filename for reading: $!";

As with the shell, in Perl the "<" is used to open the file in read-only mode. If it succeeds, Perl allocates a brand new filehandle for you and fills in your previously undefined $handle argument with a reference to that handle.

As with the shell, in Perl the "<" is used to open the file in read-only mode. If it succeeds, Perl allocates a brand new filehandle for you and fills in your previously undefined $handle argument with a reference to that handle. (TBT)

Now you may use functions like readline, read, getc, and sysread on that handle. Probably the most common input function is the one that looks like an operator:

Now you may use functions like readline, read, getc, and sysread on that handle. Probably the most common input function is the one that looks like an operator: (TBT)

    $line = readline($handle);
    $line = <$handle>;          # same thing

Because the readline function returns undef at end of file or upon error, you will sometimes see it used this way:

Because the readline function returns undef at end of file or upon error, you will sometimes see it used this way: (TBT)

    $line = <$handle>;
    if (defined $line) {
        # do something with $line
    }
    else {
        # $line is not valid, so skip it
    }

You can also just quickly die on an undefined value this way:

You can also just quickly die on an undefined value this way: (TBT)

    $line = <$handle> // die "no input found";

However, if hitting EOF is an expected and normal event, you do not want to exit simply because you have run out of input. Instead, you probably just want to exit an input loop. You can then test to see if an actual error has caused the loop to terminate, and act accordingly:

However, if hitting EOF is an expected and normal event, you do not want to exit simply because you have run out of input. Instead, you probably just want to exit an input loop. You can then test to see if an actual error has caused the loop to terminate, and act accordingly: (TBT)

    while (<$handle>) {
        # do something with data in $_
    }
    if ($!) {
        die "unexpected error while reading from $filename: $!";
    }

A Note on Encodings: Having to specify the text encoding every time might seem a bit of a bother. To set up a default encoding for open so that you don't have to supply it each time, you can use the open pragma:

A Note on Encodings: Having to specify the text encoding every time might seem a bit of a bother. To set up a default encoding for open so that you don't have to supply it each time, you can use the open pragma: (TBT)

    use open qw< :encoding(UTF-8) >;

Once you've done that, you can safely omit the encoding part of the open mode:

Once you've done that, you can safely omit the encoding part of the open mode: (TBT)

    open($handle, "<", $filename)
        || die "$0: can't open $filename for reading: $!";

But never use the bare "<" without having set up a default encoding first. Otherwise, Perl cannot know which of the many, many, many possible flavors of text file you have, and Perl will have no idea how to correctly map the data in your file into actual characters it can work with. Other common encoding formats including "ASCII", "ISO-8859-1", "ISO-8859-15", "Windows-1252", "MacRoman", and even "UTF-16LE". See perlunitut for more about encodings.

But never use the bare "<" without having set up a default encoding first. Otherwise, Perl cannot know which of the many, many, many possible flavors of text file you have, and Perl will have no idea how to correctly map the data in your file into actual characters it can work with. Other common encoding formats including "ASCII", "ISO-8859-1", "ISO-8859-15", "Windows-1252", "MacRoman", and even "UTF-16LE". See perlunitut for more about encodings. (TBT)

書き込み用にテキストファイルを開く

When you want to write to a file, you first have to decide what to do about any existing contents of that file. You have two basic choices here: to preserve or to clobber.

When you want to write to a file, you first have to decide what to do about any existing contents of that file. You have two basic choices here: to preserve or to clobber. (TBT)

If you want to preserve any existing contents, then you want to open the file in append mode. As in the shell, in Perl you use ">>" to open an existing file in append mode. ">>" creates the file if it does not already exist.

If you want to preserve any existing contents, then you want to open the file in append mode. As in the shell, in Perl you use ">>" to open an existing file in append mode. ">>" creates the file if it does not already exist. (TBT)

    my $handle   = undef;
    my $filename = "/some/path/to/a/textfile/goes/here";
    my $encoding = ":encoding(UTF-8)";

    open($handle, ">> $encoding", $filename)
        || die "$0: can't open $filename for appending: $!";

Now you can write to that filehandle using any of print, printf, say, write, or syswrite.

Now you can write to that filehandle using any of print, printf, say, write, or syswrite. (TBT)

As noted above, if the file does not already exist, then the append-mode open will create it for you. But if the file does already exist, its contents are safe from harm because you will be adding your new text past the end of the old text.

As noted above, if the file does not already exist, then the append-mode open will create it for you. But if the file does already exist, its contents are safe from harm because you will be adding your new text past the end of the old text. (TBT)

On the other hand, sometimes you want to clobber whatever might already be there. To empty out a file before you start writing to it, you can open it in write-only mode:

On the other hand, sometimes you want to clobber whatever might already be there. To empty out a file before you start writing to it, you can open it in write-only mode: (TBT)

    my $handle   = undef;
    my $filename = "/some/path/to/a/textfile/goes/here";
    my $encoding = ":encoding(UTF-8)";

    open($handle, "> $encoding", $filename)
        || die "$0: can't open $filename in write-open mode: $!";

Here again Perl works just like the shell in that the ">" clobbers an existing file.

Here again Perl works just like the shell in that the ">" clobbers an existing file. (TBT)

As with the append mode, when you open a file in write-only mode, you can now write to that filehandle using any of print, printf, say, write, or syswrite.

As with the append mode, when you open a file in write-only mode, you can now write to that filehandle using any of print, printf, say, write, or syswrite. (TBT)

What about read-write mode? You should probably pretend it doesn't exist, because opening text files in read-write mode is unlikely to do what you would like. See perlfaq5 for details.

What about read-write mode? You should probably pretend it doesn't exist, because opening text files in read-write mode is unlikely to do what you would like. See perlfaq5 for details. (TBT)

バイナリファイルを開く

If the file to be opened contains binary data instead of text characters, then the MODE argument to open is a little different. Instead of specifying the encoding, you tell Perl that your data are in raw bytes.

If the file to be opened contains binary data instead of text characters, then the MODE argument to open is a little different. Instead of specifying the encoding, you tell Perl that your data are in raw bytes. (TBT)

    my $filename = "/some/path/to/a/binary/file/goes/here";
    my $encoding = ":raw :bytes"
    my $handle   = undef;     # this will be filled in on success

And then open as before, choosing "<", ">>", or ">" as needed:

And then open as before, choosing "<", ">>", or ">" as needed: (TBT)

    open($handle, "< $encoding", $filename)
        || die "$0: can't open $filename for reading: $!";

    open($handle, ">> $encoding", $filename)
        || die "$0: can't open $filename for appending: $!";

    open($handle, "> $encoding", $filename)
        || die "$0: can't open $filename in write-open mode: $!";

Alternately, you can change to binary mode on an existing handle this way:

Alternately, you can change to binary mode on an existing handle this way: (TBT)

    binmode($handle)    || die "cannot binmode handle";

This is especially handy for the handles that Perl has already opened for you.

This is especially handy for the handles that Perl has already opened for you. (TBT)

    binmode(STDIN)      || die "cannot binmode STDIN";
    binmode(STDOUT)     || die "cannot binmode STDOUT";

You can also pass binmode an explicit encoding to change it on the fly. This isn't exactly "binary" mode, but we still use binmode to do it:

You can also pass binmode an explicit encoding to change it on the fly. This isn't exactly "binary" mode, but we still use binmode to do it: (TBT)

  binmode(STDIN,  ":encoding(MacRoman)") || die "cannot binmode STDIN";
  binmode(STDOUT, ":encoding(UTF-8)")    || die "cannot binmode STDOUT";

Once you have your binary file properly opened in the right mode, you can use all the same Perl I/O functions as you used on text files. However, you may wish to use the fixed-size read instead of the variable-sized readline for your input.

Once you have your binary file properly opened in the right mode, you can use all the same Perl I/O functions as you used on text files. However, you may wish to use the fixed-size read instead of the variable-sized readline for your input. (TBT)

Here's an example of how to copy a binary file:

Here's an example of how to copy a binary file: (TBT)

    my $BUFSIZ   = 64 * (2 ** 10);
    my $name_in  = "/some/input/file";
    my $name_out = "/some/output/flie";

    my($in_fh, $out_fh, $buffer);

    open($in_fh,  "<", $name_in)
        || die "$0: cannot open $name_in for reading: $!";
    open($out_fh, ">", $name_out)
        || die "$0: cannot open $name_out for writing: $!";

    for my $fh ($in_fh, $out_fh)  {
        binmode($fh)               || die "binmode failed";
    }

    while (read($in_fh, $buffer, $BUFSIZ)) {
        unless (print $out_fh $buffer) {
            die "couldn't write to $name_out: $!";
        }
    }

    close($in_fh)       || die "couldn't close $name_in: $!";
    close($out_fh)      || die "couldn't close $name_out: $!";

パイプを開く

To be announced.

未定。

sysopen 経由で低レベルにファイルを開く

To be announced. Or deleted.

未定。 または削除する。

SEE ALSO

To be announced.

未定。

AUTHOR and COPYRIGHT

Copyright 2013 Tom Christiansen.

This documentation is free; you can redistribute it and/or modify it under the same terms as Perl itself.