■ベアワードのファイルハンドルをつかわない方がいい理由
近年、ベアワードのファイルハンドルを定義する方法(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でもないかぎりは)。
プラネックス
購入: 81人 クリック: 229回
購入: 81人 クリック: 229回
トラックバック - http://d.hatena.ne.jp/tokuhirom/20080601/1212315386


