2010-11-04
perlのスコープはブロック or ファイルなのだろうか
perl | |
ふとした拍子につまづいた。
以下を1個のファイル、例えば t.pl にでも書いて実行する。
package Hoge; use strict; use warnings; my $h = 1; package main; use strict; use warnings; my $h = 2; warn $h;
さあ実行結果を予測しよう。
実行結果
% perl t.pl "my" variable $h masks earlier declaration in same scope at t.pl line 9. 2 at t.pl line 10.
何でやねん。
そしてmainの中でのmy宣言を抜かすと
1 at t.pl line 9.
となる。
解
恒例の柔道家に質問してみる。俺の成長が見えない。
perlのscopeは、block or file なんじゃないかね。
packageごとにblockつくれば、エラーになるよ。
というわけでその通りにしてみたらその通りになった。
なんという微妙仕様。
1個のファイルで複数パッケージ宣言する事が滅多に無いもので今まで気付かなかった。
perlfaqをscope,file,lexicalあたりで探したがその辺の解説が見つからなかったので不貞寝する。
トラックバック - http://d.hatena.ne.jp/hirafoo/20101104

A package statement affects dynamic variables only, including those you've used "local" on, but *not* lexical variables, which are created with "my" (or "our" (or "state")).