Hatena::ブログ(Diary)

”><xmp>TokuLog 改メ tokuhirom’s blog このページをアンテナに追加 RSSフィード

アワードファイルハンドルをつかわない方がいい理由

最近このファイルハンドルって奴を見なくなりましたね。古くさいからでしょうか。

http://perl-mongers.org/2008/06/perl_file_glob.html

近年、ベアワードファイルハンドルを定義する方法(open FH, q{<}, $filename)のかわりに my でファイルハンドルを定義する方法(open my $fh, q{<}, $filename)をつかうことが推奨されています。この方法が推奨されているのにはちゃんとした理由があります。

PBP でも後者が推奨されていますし、Perl::Critic でもベアワードファイルハンドルは非推奨とされています(Perl::Critic::Policy::InputOutput::ProhibitBarewordFileHandles)。

これはなぜかというと、

Using bareword symbols to refer to file handles is particularly evil because they are global, and you have no idea if that symbol already points to some other file handle. You can mitigate some of that risk by localizing the symbol first, but that's pretty ugly. Since Perl 5.6, you can use an undefined scalar variable as a lexical reference to an anonymous filehandle. Alternatively, see the IO::Handle or IO::File or FileHandle modules for an object-oriented approach.

    open FH, '<', $some_file;           #not ok
    open my $fh, '<', $some_file;       #ok
    my $fh = IO::File->new($some_file); #ok

There are three exceptions: STDIN, STDOUT and STDERR. These three standard filehandles are always package variables.

アワードファイルハンドルグローバル変数だからです。なんでもかんでもグローバル変数をつかっているとろくなことにならないのは皆さんご存知のとおりです。レキシカルにできるものはできるだけレキシカルにしておいた方がいいのはいうまでもありません。

下記のように、呼びだした先の関数や全然関係ないところで同じ名前のベアワードファイルハンドルをつかわれると勝手に操作されてしまう可能性があるのです!

use strict;

sub foo {
    open FILE, '<', '/etc/passwd' or die $!;
}

open FILE, '<', '/etc/hosts' or die $!;
foo();
print <FILE>;
close FILE;

というわけで、open FH ではなく open my $fh をつかうべきなのです(あなたがgolpherでもないかぎりは)。

dayflowerdayflower 2008/06/02 14:27 あとベアワードは無引数プロトタイプな関数(定数とか)とバッティングするってじっちゃんもといPBPがいってました。

use strict;

sub FILE() { }

open FILE, ’>’, ’dummy.txt’ or die $!;
close FILE;

投稿したコメントは管理者が承認するまで公開されません。

スパム対策のためのダミーです。もし見えても何も入力しないでください
ゲスト


画像認証

トラックバック - http://d.hatena.ne.jp/tokuhirom/20080601/1212315386