NAME

perlopentut - Perl でいろんなものを開くためのチュートリアル


DESCRIPTION

Perl には、ファイルを開くための 2 つの単純な組み込みの手段があります: 便利さのためのシェル風の方法と、正確性のための C 風の方法です。 シェル風の方法には 2 引数と 3 引数があり、ファイル名の扱いに関して 異なった動作をします。 選択はあなた次第です。


シェル風に開く

Perl の open 関数は、シェルでのコマンドラインのリダイレクトをまねて 設計されています。 以下はシェルでの基本的な例です:

    $ myprogram file1 file2 file3
    $ myprogram    <  inputfile
    $ myprogram    >  outputfile
    $ myprogram    >> outputfile
    $ myprogram    |  otherprogram 
    $ otherprogram |  myprogram

そして以下はもう少し高度な例です:

    $ otherprogram      | myprogram f1 - f2
    $ otherprogram 2>&1 | myprogram -
    $ myprogram     <&3
    $ myprogram     >&4

上述のような方法に慣れているプログラマにとっては、Perl がシェルと事実上 同じ文法を使った親しんでいる構造に直接対応していることは 学ぶのが容易になります。

単純に開く

open 関数は 2 つの引数を取ります: 1 つめはファイルハンドルで、 2 つめは何を開くかとどう開くかで構成される単一の文字列です。 open は成功すると真を返し、失敗すると偽を返して特殊変数 $! に システムエラーを反映します。 指定されたファイルハンドルが以前に開かれていた場合は、暗黙の内に まず閉じられます。

例えば:

    open(INFO,      "datafile") || die("can't open datafile: $!");
    open(INFO,   "<  datafile") || die("can't open datafile: $!");
    open(RESULTS,">  runstats") || die("can't open runstats: $!");
    open(LOG,    ">> logfile ") || die("can't open logfile:  $!");

句読点が少ない方が好みなら、以下のようにも書けます:

    open INFO,   "<  datafile"  or die "can't open datafile: $!";
    open RESULTS,">  runstats"  or die "can't open runstats: $!";
    open LOG,    ">> logfile "  or die "can't open logfile:  $!";

いくつか気がつくことがあります。 まず、先頭の「大なり」は省略可能です。 省略されると、Perl はファイルを読み込みのために開きたいと仮定します。

Note also that the first example uses the || logical operator, and the second uses or, which has lower precedence. 後者の例で || を使うと、実際には以下のような意味になり

    open INFO, ( "<  datafile"  || die "can't open datafile: $!" );

あなたが望んでいるのと全く違うことになります。

他の注意するべき重要なこととしては、シェルと同様、ファイル名の前後の 空白は無視されることです。 これはよいことです; なぜなら、以下のものが違うことをすることは 望まないだろうからです:

    open INFO,   "<datafile"   
    open INFO,   "< datafile" 
    open INFO,   "<  datafile"

周りの空白を無視することは、ファイル名を別のファイルから読み込んで、 開く前に空白を取り除くのを忘れたときにも助けになります:

    $filename = <INFO>;         # oops, \n still there
    open(EXTRA, "< $filename") || die "can't open $filename: $!";

これはバグではありません、仕様です。 open はどのようにファイルを開くかを指定するのにリダイレクトの矢印を 使うことでシェルを真似ているので、ファイル名の周りの空白についても 同じように扱います。 行儀の悪い名前のファイルにアクセスするためには、 魔法を解く を参照してください。

また、3 引数版の open もあって、これは特殊なリダイレクト文字を 独立した引数にしたものです:

    open( INFO, ">", $datafile ) || die "Can't create $datafile: $!";

この場合、開くファイル名は $datafile の実際の文字列なので、 $datafile に開くモードに影響を与える文字や、 2 引数版では吸収されるファイル名の先頭の空白が含まれているかどうかを 心配する必要はありません。 また、不必要な文字列変換が削減されるのもよいことです。

間接ファイルハンドル

open の最初の引数は、ファイルハンドルへのリファレンスにすることも出来ます。 perl 5.6.0 以降、引数が初期化されていない場合、Perl は 以下のように、自動的にファイルハンドルを作成して、それへのリファレンスを 最初の引数に設定します:

    open( my $in, $infile )   or die "Couldn't read $infile: $!";
    while ( <$in> ) {
        # do something with $_
    }
    close $in;

間接ファイルハンドルは、名前空間管理をより容易にします。 ファイルハンドルは現在のパッケージに対してグローバルなので、 二つのサブルーチンが INFILE を開こうとすると衝突します。 二つの関数が my $infil のように間接ファイルハンドルで開いていると、 衝突は発生せず、将来の衝突を気にする必要もありません。

もう一つの便利は振る舞いとして、間接ファイルハンドルは、スコープ外に出るか undef にされると、自動的に閉じます:

    sub firstline {
        open( my $in, shift ) && return scalar <$in>;
        # no close() required
    }

パイプを開く

C では、標準 I/O ライブラリを使ってファイルを開きたいときは fopen を 使いますが、パイプを開くときには popen 関数を使います。 しかし、シェルでは、単に違うリダイレクト文字を使います。 これは Perl の場合にも当てはまります。 open 呼び出しは同じままです -- 単にその引数が変わります。

先頭の文字がパイプ記号の場合、open は starts up a new command and opens a write-only filehandle leading into that command. This lets you write into that handle and have what you write show up on that command's standard input. 例えば: (TBT)

    open(PRINTER, "| lpr -Plp1")    || die "can't run lpr: $!";
    print PRINTER "stuff\n";
    close(PRINTER)                  || die "can't close lpr: $!";

末尾の文字がパイプの場合、you start up a new command and open a read-only filehandle leading out of that command. This lets whatever that command writes to its standard output show up on your handle for reading. 例えば: (TBT)

    open(NET, "netstat -i -n |")    || die "can't fork netstat: $!";
    while (<NET>) { }               # do something with input
    close(NET)                      || die "can't close netstat: $!";

What happens if you try to open a pipe to or from a non-existent command? If possible, Perl will detect the failure and set $! as usual. But if the command contains special shell characters, such as > or *, called 'metacharacters', Perl does not execute the command directly. Instead, Perl runs the shell, which then tries to run the command. This means that it's the shell that gets the error indication. In such a case, the open call will only indicate failure if Perl can't even run the shell. See How can I capture STDERR from an external command? in perlfaq8 to see how to cope with this. There's also an explanation in perlipc. (TBT)

双方向パイプを開きたい場合は、IPC::Open2 ライブラリが使えます。 Bidirectional Communication with Another Process in perlipc を 参照してください。

"-" ファイル

再び標準シェルの機能に合わせるように、Perl の open 関数は、名前がマイナス一つ "-" だけのファイルを特別に扱います。 読み込み用にマイナスを開くと、実際には標準入力にアクセスします。 書き込み用にマイナスを開くと、実際には標準出力にアクセスします。

If minus can be used as the default input or default output, what happens if you open a pipe into or out of minus? What's the default command it would run? The same script as you're currently running! This is actually a stealth fork hidden inside an open call. 詳しくは Safe Pipe Opens in perlipc を参照してください。 (TBT)

読み書きを混ぜる

読み書きアクセス双方を指定することは可能です。 必要なことはリダイレクトの前に "+" の文字を加えるだけです。 But as in the shell, using a less-than on a file never creates a new file; it only opens an existing one. On the other hand, using a greater-than always clobbers (truncates to zero length) an existing file, or creates a brand-new one if there isn't an old one. Adding a "+" for read-write doesn't affect whether it only works on existing files or always clobbers existing ones. (TBT)

    open(WTMP, "+< /usr/adm/wtmp") 
        || die "can't open /usr/adm/wtmp: $!";
    open(SCREEN, "+> lkscreen")
        || die "can't open lkscreen: $!";
    open(LOGFILE, "+>> /var/log/applog")
        || die "can't open /var/log/applog: $!";

一つ目のものは新しいファイルを作ることはなく、二つ目のものは常に古い ファイルを上書きします。 三つ目のものは必要があれば新しいファイルを作りますが、古いファイルを 上書きせず、ファイルのどの地点でも読み込むことができますが、 書き込みは常に末尾に行われます。 In short, the first case is substantially more common than the second and third cases, which are almost always wrong. (If you know C, the plus in Perl's open is historically derived from the one in C's fopen(3S), which it ultimately calls.) (TBT)

実際、when it comes to updating a file, unless you're working on a binary file as in the WTMP case above, you probably don't want to use this approach for updating. Instead, Perl's -i flag comes to the rescue. The following command takes all the C, C++, or yacc source or header files and changes all their foo's to bar's, leaving the old version in the original filename with a ".orig" tacked on the end: (TBT)

    $ perl -i.orig -pe 's/\bfoo\b/bar/g' *.[Cchy]

This is a short cut for some renaming games that are really the best way to update textfiles. See the second question in perlfaq5 for more details. (TBT)

フィルタ

One of the most common uses for open is one you never even notice. When you process the ARGV filehandle using <ARGV>, Perl actually does an implicit open on each file in @ARGV. Thus a program called like this: (TBT)

    $ myprogram file1 file2 file3

can have all its files opened and processed one at a time using a construct no more complex than: (TBT)

    while (<>) {
        # do something with $_
    }

If @ARGV is empty when the loop first begins, Perl pretends you've opened up minus, that is, the standard input. In fact, $ARGV, the currently open file during <ARGV> processing, is even set to "-" in these circumstances. (TBT)

You are welcome to pre-process your @ARGV before starting the loop to make sure it's to your liking. One reason to do this might be to remove command options beginning with a minus. いつでも自分で単純なものを作ることができる一方、 Getopts モジュールはこれを行うのによいものです: (TBT)

    use Getopt::Std;
    # -v, -D, -o ARG, sets $opt_v, $opt_D, $opt_o
    getopts("vDo:");
    # -v, -D, -o ARG, sets $args{v}, $args{D}, $args{o}
    getopts("vDo:", \%args);

あるいは、名前付きの引数を使えるようにするための 標準の Getopt::Long モジュールもあります:

    use Getopt::Long;
    GetOptions( "verbose"  => \$verbose,        # --verbose
                "Debug"    => \$debug,          # --Debug
                "output=s" => \$output );       
            # --output=somestring or --output somestring

引数を前処理するためのもう一つの理由は、空引数リストの時は デフォルトで全てのファイルとする場合です:

    @ARGV = glob("*") unless @ARGV;

プレーンなテキストファイル以外をフィルタリングすることもできます。 これはもちろん少し静かなので、途中でそれに言及したいかもしれません。

    @ARGV = grep { -f && -T } @ARGV;

もし -n-p のコマンドラインオプションを使っているなら、 @ARGV への変更は BEGIN{} ブロックで行うべきです。

Remember that a normal open has special properties, in that it might call fopen(3S) or it might called popen(3S), depending on what its argument looks like; that's why it's sometimes called "magic open". Here's an example: (TBT)

    $pwdinfo = `domainname` =~ /^(\(none\))?$/
                    ? '< /etc/passwd'
                    : 'ypcat passwd |';
    open(PWD, $pwdinfo)                 
                or die "can't open $pwdinfo: $!";

This sort of thing also comes into play in filter processing. Because <ARGV> processing employs the normal, shell-style Perl open, it respects all the special things we've already seen: (TBT)

    $ myprogram f1 "cmd1|" - f2 "cmd2|" f3 < tmpfile

That program will read from the file f1, the process cmd1, standard input (tmpfile in this case), the f2 file, the cmd2 command, and finally the f3 file. (TBT)

Yes, this also means that if you have files named "-" (and so on) in your directory, they won't be processed as literal files by open. You'll need to pass them as "./-", much as you would for the rm program, or you could use sysopen as described below. (TBT)

One of the more interesting applications is to change files of a certain name into pipes. For example, to autoprocess gzipped or compressed files by decompressing them with gzip: (TBT)

    @ARGV = map { /^\.(gz|Z)$/ ? "gzip -dc $_ |" : $_  } @ARGV;

Or, if you have the GET program installed from LWP, you can fetch URLs before processing them: (TBT)

    @ARGV = map { m#^\w+://# ? "GET $_ |" : $_ } @ARGV;

It's not for nothing that this is called magic <ARGV>. Pretty nifty, eh? (TBT)


C 風に開く

If you want the convenience of the shell, then Perl's open is definitely the way to go. On the other hand, if you want finer precision than C's simplistic fopen(3S) provides you should look to Perl's sysopen, which is a direct hook into the open(2) system call. That does mean it's a bit more involved, but that's the price of precision. (TBT)

sysopen は 3 (または 4) 引数を取ります。

    sysopen HANDLE, PATH, FLAGS, [MASK]

The HANDLE argument is a filehandle just as with open. The PATH is a literal path, one that doesn't pay attention to any greater-thans or less-thans or pipes or minuses, nor ignore whitespace. If it's there, it's part of the path. The FLAGS argument contains one or more values derived from the Fcntl module that have been or'd together using the bitwise "|" operator. The final argument, the MASK, is optional; if present, it is combined with the user's current umask for the creation mode of the file. You should usually omit this. (TBT)

Although the traditional values of read-only, write-only, and read-write are 0, 1, and 2 respectively, this is known not to hold true on some systems. Instead, it's best to load in the appropriate constants first from the Fcntl module, which supplies the following standard flags: (TBT)

    O_RDONLY            Read only
    O_WRONLY            Write only
    O_RDWR              Read and write
    O_CREAT             Create the file if it doesn't exist
    O_EXCL              Fail if the file already exists
    O_APPEND            Append to the file
    O_TRUNC             Truncate the file
    O_NONBLOCK          Non-blocking access

Less common flags that are sometimes available on some operating systems include O_BINARY, O_TEXT, O_SHLOCK, O_EXLOCK, O_DEFER, O_SYNC, O_ASYNC, O_DSYNC, O_RSYNC, O_NOCTTY, O_NDELAY and O_LARGEFILE. Consult your open(2) manpage or its local equivalent for details. (Note: starting from Perl release 5.6 the O_LARGEFILE flag, if available, is automatically added to the sysopen() flags because large files are the default.) (TBT)

Here's how to use sysopen to emulate the simple open calls we had before. We'll omit the || die $! checks for clarity, but make sure you always check the return values in real code. These aren't quite the same, since open will trim leading and trailing whitespace, but you'll get the idea. (TBT)

ファイルを読み込み用に開くには:

    open(FH, "< $path");
    sysopen(FH, $path, O_RDONLY);

ファイルを書き込み用に開いて、必要なら新しいファイルを作り、そうでなければ 古いファイルを切り詰めるには:

    open(FH, "> $path");
    sysopen(FH, $path, O_WRONLY | O_TRUNC | O_CREAT);

ファイルを追加用に開いて、もし必要なら新しいファイルを作るには:

    open(FH, ">> $path");
    sysopen(FH, $path, O_WRONLY | O_APPEND | O_CREAT);

既に存在しているファイルを更新用に開くには:

    open(FH, "+< $path");
    sysopen(FH, $path, O_RDWR);

And here are things you can do with sysopen that you cannot do with a regular open. As you'll see, it's just a matter of controlling the flags in the third argument. (TBT)

To open a file for writing, creating a new file which must not previously exist: (TBT)

    sysopen(FH, $path, O_WRONLY | O_EXCL | O_CREAT);

To open a file for appending, where that file must already exist: (TBT)

    sysopen(FH, $path, O_WRONLY | O_APPEND);

To open a file for update, creating a new file if necessary: (TBT)

    sysopen(FH, $path, O_RDWR | O_CREAT);

To open a file for update, where that file must not already exist: (TBT)

    sysopen(FH, $path, O_RDWR | O_EXCL | O_CREAT);

To open a file without blocking, creating one if necessary: (TBT)

    sysopen(FH, $path, O_WRONLY | O_NONBLOCK | O_CREAT);

権限モード

If you omit the MASK argument to sysopen, Perl uses the octal value 0666. The normal MASK to use for executables and directories should be 0777, and for anything else, 0666. (TBT)

Why so permissive? Well, it isn't really. The MASK will be modified by your process's current umask. A umask is a number representing disabled permissions bits; that is, bits that will not be turned on in the created files' permissions field. (TBT)

For example, if your umask were 027, then the 020 part would disable the group from writing, and the 007 part would disable others from reading, writing, or executing. Under these conditions, passing sysopen 0666 would create a file with mode 0640, since 0666 & ~027 is 0640. (TBT)

You should seldom use the MASK argument to sysopen(). That takes away the user's freedom to choose what permission new files will have. Denying choice is almost always a bad thing. One exception would be for cases where sensitive or private data is being stored, such as with mail folders, cookie files, and internal temporary files. (TBT)


わかりにくい開くときの小技

ファイルを再び開く(dup)

Sometimes you already have a filehandle open, and want to make another handle that's a duplicate of the first one. In the shell, we place an ampersand in front of a file descriptor number when doing redirections. For example, 2>&1 makes descriptor 2 (that's STDERR in Perl) be redirected into descriptor 1 (which is usually Perl's STDOUT). The same is essentially true in Perl: a filename that begins with an ampersand is treated instead as a file descriptor if a number, or as a filehandle if a string. (TBT)

    open(SAVEOUT, ">&SAVEERR") || die "couldn't dup SAVEERR: $!";
    open(MHCONTEXT, "<&4")     || die "couldn't dup fd4: $!";

That means that if a function is expecting a filename, but you don't want to give it a filename because you already have the file open, you can just pass the filehandle with a leading ampersand. It's best to use a fully qualified handle though, just in case the function happens to be in a different package: (TBT)

    somefunction("&main::LOGFILE");

This way if somefunction() is planning on opening its argument, it can just use the already opened handle. This differs from passing a handle, because with a handle, you don't open the file. Here you have something you can pass to open. (TBT)

If you have one of those tricky, newfangled I/O objects that the C++ folks are raving about, then this doesn't work because those aren't a proper filehandle in the native Perl sense. You'll have to use fileno() to pull out the proper descriptor number, assuming you can: (TBT)

    use IO::Socket;
    $handle = IO::Socket::INET->new("www.perl.com:80");
    $fd = $handle->fileno;
    somefunction("&$fd");  # not an indirect function call

しかし、単に普通のファイルハンドルを使う方が簡単でしょう (そして確実に高速です):

    use IO::Socket;
    local *REMOTE = IO::Socket::INET->new("www.perl.com:80");
    die "can't connect" unless defined(fileno(REMOTE));
    somefunction("&main::REMOTE");

If the filehandle or descriptor number is preceded not just with a simple "&" but rather with a "&=" combination, then Perl will not create a completely new descriptor opened to the same place using the dup(2) system call. Instead, it will just make something of an alias to the existing one using the fdopen(3S) library call. This is slightly more parsimonious of systems resources, although this is less a concern these days. Here's an example of that: (TBT)

    $fd = $ENV{"MHCONTEXTFD"};
    open(MHCONTEXT, "<&=$fd")   or die "couldn't fdopen $fd: $!";

If you're using magic <ARGV>, you could even pass in as a command line argument in @ARGV something like "<&=$MHCONTEXTFD", but we've never seen anyone actually do this. (TBT)

魔法を解く

Perl is more of a DWIMmer language than something like Java--where DWIM is an acronym for "do what I mean". But this principle sometimes leads to more hidden magic than one knows what to do with. In this way, Perl is also filled with dweomer, an obscure word meaning an enchantment. Sometimes, Perl's DWIMmer is just too much like dweomer for comfort. (TBT)

If magic open is a bit too magical for you, you don't have to turn to sysopen. To open a file with arbitrary weird characters in it, it's necessary to protect any leading and trailing whitespace. Leading whitespace is protected by inserting a "./" in front of a filename that starts with whitespace. Trailing whitespace is protected by appending an ASCII NUL byte ("\0") at the end of the string. (TBT)

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

This assumes, of course, that your system considers dot the current working directory, slash the directory separator, and disallows ASCII NULs within a valid filename. Most systems follow these conventions, including all POSIX systems as well as proprietary Microsoft systems. The only vaguely popular system that doesn't work this way is the "Classic" Macintosh system, which uses a colon where the rest of us use a slash. Maybe sysopen isn't such a bad idea after all. (TBT)

If you want to use <ARGV> processing in a totally boring and non-magical way, you could do this first: (TBT)

    #   "Sam sat on the ground and put his head in his hands.  
    #   'I wish I had never come here, and I don't want to see 
    #   no more magic,' he said, and fell silent."
    for (@ARGV) { 
        s#^([^./])#./$1#;
        $_ .= "\0";
    } 
    while (<>) {  
        # now process $_
    }

But be warned that users will not appreciate being unable to use "-" to mean standard input, per the standard convention. (TBT)

Paths as Opens

どうやって Perl の warn 関数と die 関数が以下のようなメッセージを 生成するかに気付いたでしょう:

    Some warning at scriptname line 29, <FH> line 7.

これは、あなたがファイルハンドル FH を開いて、そこから 7 レコードを 読み込んだからです。 しかし、ハンドルではなく、ファイル名はどうでしょう?

もし strict refs を有効にしていないか、一時的に無効にしているなら、 する必要があるのは以下のことだけです:

    open($path, "< $path") || die "can't open $path: $!";
    while (<$path>) {
        # whatever
    }

ファイルのパス名をハンドルとして使っているので、以下のような警告が 出ます

    Some warning at scriptname line 29, </etc/motd> line 7.

1 引数の open

Remember how we said that Perl's open took two arguments? That was a passive prevarication. You see, it can also take just one argument. If and only if the variable is a global variable, not a lexical, you can pass open just one argument, the filehandle, and it will get the path from the global scalar variable of the same name. (TBT)

    $FILE = "/etc/motd";
    open FILE or die "can't open $FILE: $!";
    while (<FILE>) {
        # whatever
    }

Why is this here? Someone has to cater to the hysterical porpoises. It's something that's been in Perl since the very beginning, if not before. (TBT)

STDIN と STDOUT を扱う

STDOUT に関する一つの利口な行動は、プログラムの終了時に 明示的に閉じることです。

    END { close(STDOUT) || die "can't close stdout: $!" }

これをしないままで、このプログラムがコマンドラインリダイレクトによって ディスクをいっぱいにしてしまっても、失敗状態でエラー終了しません。

与えられた STDIN と STDOUT を受け入れる必要はありません。 もし望むなら、これらを開き直せます。

    open(STDIN, "< datafile")
        || die "can't open datafile: $!";
    open(STDOUT, "> output")
        || die "can't open output: $!";

それからこれらは直接アクセスしたり子プロセスに渡したりできます。 これらは、プログラムの起動時にコマンドラインからリダイレクトが 与えられたかのように動作します。

これらをパイプにつなぐ方がより興味深いでしょう。 例えば:

    $pager = $ENV{PAGER} || "(less || more)";
    open(STDOUT, "| $pager")
        || die "can't fork a pager: $!";

これによって、プログラムの標準出力がが既にページャとパイプで つながれているかのように見えます。 このようなことはまた、自分自身を暗黙に fork したものと結合するためにも 使えます。 自分自身のプログラムの別のプロセスでで後処理を扱いたい場合、 以下のようにできます:

    head(100);
    while (<>) {
        print;
    }
    sub head {
        my $lines = shift || 20;
        return if $pid = open(STDOUT, "|-");       # return if parent
        die "cannot fork: $!" unless defined $pid;
        while (<STDIN>) {
            last if --$lines < 0;
            print;
        } 
        exit;
    }

このテクニックは、繰り返しプッシュすることで、出力ストリームに好きなだけ 多くのフィルタを適用できます。


その他の I/O 関連の話題

これらの話題は実際には opensysopen に関連したものではありませんが、 ファイルを開くときに行うことに影響を与えます。

ファイルでないファイルを開く

ファイルがファイルでないときは? えっと、プレーンファイルでないものの時、と言いたいんですよね。 まず、念のために、それがシンボリックリンクかどうかを調べます。

    if (-l $file || ! -f _) {
        print "$file is not a plain file\n";
    }

えーと、ファイルの他にどんな種類のファイルがあるのでしょう? ディレクトリ、シンボリックリンク、名前付きパイプ、Unix ドメインソケット、 キャラクタデバイス、ブロックデバイスです。 これらも全てファイルです -- 単に プレーン ファイルではないと いうだけです。 これはテキストファイルと同じ問題ではありません。 全てのテキストファイルがプレーンファイルではありません。 全てのプレーンファイルがテキストファイルではありません。 これが、-f-T のファイルテストが分離している理由です。

ディレクトリを開くには、opendir 関数を使って、それから readdir で処理します; もし必要なら注意深くディレクトリ名を復元します:

    opendir(DIR, $dirname) or die "can't opendir $dirname: $!";
    while (defined($file = readdir(DIR))) {
        # do something with "$dirname/$file"
    }
    closedir(DIR);

ディレクトリを再帰的に処理したい場合は、File::Find モジュールを使った方が いいでしょう。 例えば、これは全てのファイルを再帰的に表示して、もしファイルが ディレクトリの場合は末尾にスラッシュを追加します。

    @ARGV = qw(.) unless @ARGV;
    use File::Find;
    find sub { print $File::Find::name, -d && '/', "\n" }, @ARGV;

以下は、特定のディレクトリ以下から偽のシンボリックリンクを全て探します:

    find sub { print "$File::Find::name\n" if -l && !-e }, $dir;

上述したように、シンボリックリンクの場合、単にそれが指しているもの振りを することができます。 あるいは、もしそれが 何を 指しているのかを知りたい場合は、 readlink を呼び出します:

    if (-l $file) {
        if (defined($whither = readlink($file))) {
            print "$file points to $whither\n";
        } else {
            print "$file points nowhere: $!\n";
        } 
    }

名前付きパイプを開く

名前付きパイプは別の問題です。 You pretend they're regular files, but their opens will normally block until there is both a reader and a writer. You can read more about them in Named Pipes in perlipc. Unix-domain sockets are rather different beasts as well; they're described in Unix-Domain TCP Clients and Servers in perlipc. (TBT)

When it comes to opening devices, it can be easy and it can be tricky. We'll assume that if you're opening up a block device, you know what you're doing. The character devices are more interesting. These are typically used for modems, mice, and some kinds of printers. This is described in How do I read and write the serial port? in perlfaq8 It's often enough to open them carefully: (TBT)

    sysopen(TTYIN, "/dev/ttyS1", O_RDWR | O_NDELAY | O_NOCTTY)
                # (O_NOCTTY no longer needed on POSIX systems)
        or die "can't open /dev/ttyS1: $!";
    open(TTYOUT, "+>&TTYIN")
        or die "can't dup TTYIN: $!";
    $ofh = select(TTYOUT); $| = 1; select($ofh);
    print TTYOUT "+++at\015";
    $answer = <TTYIN>;

With descriptors that you haven't opened using sysopen, such as sockets, you can set them to be non-blocking using fcntl: (TBT)

    use Fcntl;
    my $old_flags = fcntl($handle, F_GETFL, 0) 
        or die "can't get flags: $!";
    fcntl($handle, F_SETFL, $old_flags | O_NONBLOCK) 
        or die "can't set non blocking: $!";

Rather than losing yourself in a morass of twisting, turning ioctls, all dissimilar, if you're going to manipulate ttys, it's best to make calls out to the stty(1) program if you have it, or else use the portable POSIX interface. To figure this all out, you'll need to read the termios(3) manpage, which describes the POSIX interface to tty devices, and then POSIX, which describes Perl's interface to POSIX. There are also some high-level modules on CPAN that can help you with these games. Check out Term::ReadKey and Term::ReadLine. (TBT)

ソケットを開く

他の何を開けるの? ソケットを使った接続を開くには、Perl の 2 つの open 関数のどちらも 使いません。 そのためには Sockets: Client/Server Communication in perlipc を 参照してください。 以下は例です。 これを実行すると、FH を双方向ファイルハンドルとして使えます。

    use IO::Socket;
    local *FH = IO::Socket::INET->new("www.perl.com:80");

URL を開くには、CPAN にある LWP モジュールがぴったりです。 ファイルハンドルのインターフェースはないですが、 それでも簡単に文書の中身を得られます:

    use LWP::Simple;
    $doc = get('http://www.linpro.no/lwp/');

バイナリファイル

On certain legacy systems with what could charitably be called terminally convoluted (some would say broken) I/O models, a file isn't a file--at least, not with respect to the C standard I/O library. On these old systems whose libraries (but not kernels) distinguish between text and binary streams, to get files to behave properly you'll have to bend over backwards to avoid nasty problems. On such infelicitous systems, sockets and pipes are already opened in binary mode, and there is currently no way to turn that off. With files, you have more options. (TBT)

Another option is to use the binmode function on the appropriate handles before doing regular I/O on them: (TBT)

    binmode(STDIN);
    binmode(STDOUT);
    while (<STDIN>) { print }

Passing sysopen a non-standard flag option will also open the file in binary mode on those systems that support it. This is the equivalent of opening the file normally, then calling binmode on the handle. (TBT)

    sysopen(BINDAT, "records.data", O_RDWR | O_BINARY)
        || die "can't open records.data: $!";

Now you can use read and print on that handle without worrying about the non-standard system I/O library breaking your data. It's not a pretty picture, but then, legacy systems seldom are. CP/M will be with us until the end of days, and after. (TBT)

On systems with exotic I/O systems, it turns out that, astonishingly enough, even unbuffered I/O using sysread and syswrite might do sneaky data mutilation behind your back. (TBT)

    while (sysread(WHENCE, $buf, 1024)) {
        syswrite(WHITHER, $buf, length($buf));
    }

Depending on the vicissitudes of your runtime system, even these calls may need binmode or O_BINARY first. Systems known to be free of such difficulties include Unix, the Mac OS, Plan 9, and Inferno. (TBT)

ファイルのロック

マルチタスク環境では、あなたが触ろうとしているファイルと同じファイルを 他のプロセスが衝突しないように気をつける必要があります。 しばしば、ファイルを読み込みまたは書き込みするために、それぞれ 共有ロックと排他ロックが必要になります。 あるいは、単に排他ロックしかないような振りをするかもしれません。

決して、ファイルの存在 -e $file をロック指示に使わないでください; なぜならファイルの存在のテストとその作成の間に競合条件があるからです。 存在チェックとファイル作成のわずかな間に、他のプロセスがファイルを作る 可能性があります。 原子性は危機的です。

Perl でのもっとも移植性のあるロックインターフェースは、 flock 関数によるものです; この単純さは、SysV や Windows のような、 これに直接対応していないシステムでもエミュレートされています。 基礎となる動作はこれがどのように働くかに影響を与えるので、 あなたが使うシステムの Perl で flock がどのように実装されているかを 学ぶべきです。

ファイルロックは、他のプロセスが I/O 操作を行うことからロックするもの ではありません。 ファイルロックは、他のプロセスの I/O 操作をロックするのではなく、他の プロセスがロックを得ようとすることをロックします。 ロックは勧告的なので、あるプロセスがロックを使っていても、他の プロセスがロックを使っていなければ、全ては台無しになります。

デフォルトでは、flock 呼び出しは、ロックが得られるまでブロックします。 共有ロック要求は、誰も排他ロックを持っていない状態になれば直ちに 受け入れられます。 排他ロック要求は、誰もあらゆる種類のロックを守っていない状態になれば 与えられます。 ロックはファイル名に対してではなく、ファイル記述子について与えられます。 ファイルを開かずにファイルをロックすることはできませんし、ファイルを閉じた 後もロックを持ったままにすることもできません。

以下はファイルに対してブロックする共有ロックを得る方法で、 典型的には読み込み時に使われます:

    use 5.004;
    use Fcntl qw(:DEFAULT :flock);
    open(FH, "< filename")  or die "can't open filename: $!";
    flock(FH, LOCK_SH)      or die "can't lock filename: $!";
    # now read from FH

LOCK_NB を使うことでブロックしないロックも得られます。

    flock(FH, LOCK_SH | LOCK_NB)
        or die "can't lock filename: $!";

ブロックするときに警告することで、よりユーザーにやさしい振る舞いを することは有用です:

    use 5.004;
    use Fcntl qw(:DEFAULT :flock);
    open(FH, "< filename")  or die "can't open filename: $!";
    unless (flock(FH, LOCK_SH | LOCK_NB)) {
        $| = 1;
        print "Waiting for lock...";
        flock(FH, LOCK_SH)  or die "can't lock filename: $!";
        print "got it.\n"
    } 
    # now read from FH

(典型的には書き込みのために) 排他ロックを得るためには、慎重になる 必要があります。 We sysopen the file so it can be locked before it gets emptied. You can get a nonblocking version using LOCK_EX | LOCK_NB. (TBT)

    use 5.004;
    use Fcntl qw(:DEFAULT :flock);
    sysopen(FH, "filename", O_WRONLY | O_CREAT)
        or die "can't open filename: $!";
    flock(FH, LOCK_EX)
        or die "can't lock filename: $!";
    truncate(FH, 0)
        or die "can't truncate filename: $!";
    # now write to FH

Finally, due to the uncounted millions who cannot be dissuaded from wasting cycles on useless vanity devices called hit counters, here's how to increment a number in a file safely: (TBT)

    use Fcntl qw(:DEFAULT :flock);
    sysopen(FH, "numfile", O_RDWR | O_CREAT)
        or die "can't open numfile: $!";
    # autoflush FH
    $ofh = select(FH); $| = 1; select ($ofh);
    flock(FH, LOCK_EX)
        or die "can't write-lock numfile: $!";
    $num = <FH> || 0;
    seek(FH, 0, 0)
        or die "can't rewind numfile : $!";
    print FH $num+1, "\n"
        or die "can't write numfile: $!";
    truncate(FH, tell(FH))
        or die "can't truncate numfile: $!";
    close(FH)
        or die "can't close numfile: $!";

IO 層

Perl 5.8.0 で、"PerlIO" と呼ばれる新しい I/O フレームワークが 導入されました。 これは Perl で発生する全ての I/O のための新しい「配管」です; ほとんど全ての部分では単に今まで通りに動作しますが、 but PerlIO also brought in some new features such as the ability to think of I/O as "layers". One I/O layer may in addition to just moving the data also do transformations on the data. Such transformations may include compression and decompression, encryption and decryption, and transforming between various character encodings. (TBT)

PerlIO の機能に関する完全な議論はこのチュートリアルの対象外ですが、 層が使われていることをどうやって認識するかを以下に示します:

PerlIO に関するより詳細な議論については PerlIO を参照してください; Unicode と I/O に関するより詳細な議論については perluniintro を 参照してください。


SEE ALSO

perlfunc(1)open 及び sysopen 関数; システムの open(2), dup(2), fopen(3), fdopen(3) の man ページ; POSIX 文書。


AUTHOR and COPYRIGHT

Copyright 1998 Tom Christiansen.

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

Irrespective of its distribution, all code examples in these files are hereby placed into the public domain. You are permitted and encouraged to use this code in your own programs for fun or for profit as you see fit. A simple comment in the code giving credit would be courteous but is not required.


HISTORY

First release: Sat Jan 9 08:09:11 MST 1999