だるろぐ

2010-11-04

perlのスコープはブロック or ファイルなのだろうか

| 01:38 | perlのスコープはブロック or ファイルなのだろうかを含むブックマーク

ふとした拍子につまづいた。

以下を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.

となる。


恒例の柔道家に質問してみる。俺の成長が見えない。

perlscopeは、block or file なんじゃないかね。

packageごとにblockつくれば、エラーになるよ。

というわけでその通りにしてみたらその通りになった。

なんという微妙仕様。

1個のファイルで複数パッケージ宣言する事が滅多に無いもので今まで気付かなかった。


perlfaqをscope,file,lexicalあたりで探したがその辺の解説が見つからなかったので不貞寝する。

YuichirouYuichirou 2010/11/04 16:13 perldoc -f packageより:
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")).

hirafoohirafoo 2010/11/04 23:23 おぉありがとうございます。packageでしたか、そのまんまですね。


事務用品 名刺 デザイン