由於常量是子程序,您可以通過調用它們作爲方法位已被覆蓋到死亡繼承,這是一個不同的東西。
如果你知道你只在一個文件時,您可以使用詞彙常量橋包:
package Parent;
our ($NO_LEVEL, $MY_LEVEL, $YOUR_LEVEL);
*NO_LEVEL = \0; # this split declaration installs aliases to numbers
*MY_LEVEL = \1; # into the lexicals. since numbers are constants
*YOUR_LEVEL = \2; # to perl, the aliased names are also constants
package Child;
# just to demonstrate that anything below can access the constants
sub printAll {
print "$NO_LEVEL $MY_LEVEL $YOUR_LEVEL\n";
}
Child->printAll; # 0 1 2
eval {$NO_LEVEL = 3} or print "error: [email protected]\n";
# error: Modification of a read-only value attempted at ...
如果你不需要perl的分配給定什麼時候死的our
聲明變得有點簡單(而且可能是一個my
):
our ($NO_LEVEL, $MY_LEVEL, $YOUR_LEVEL) = (0, 1, 2);
您可以同時仍使用簡潔的語法與小魔術帶回不斷性質:
my $constant = sub {Internals::SvREADONLY($_[$_], 1) for 0 .. $#_};
package Parent;
$constant->(our ($NO_LEVEL, $MY_LEVEL, $YOUR_LEVEL) = (0, 1, 2));
package Child;
# just to demonstrate that anything below can access the constants
sub printAll {
print "$NO_LEVEL $MY_LEVEL $YOUR_LEVEL\n"; # interpolates :)
}
Child->printAll; # 0 1 2
eval {$NO_LEVEL = 3} or print "error: [email protected]\n";
# error: Modification of a read-only value attempted at ...
當然你可以省略$constant
CODEREF和內嵌的魔力:你爲什麼把外{}在你的包
package Parent;
Internals::SvREADONLY($_, 1)
for our ($NO_LEVEL, $MY_LEVEL, $YOUR_LEVEL) = (0, 1, 2);
+1爲一個完整的答案。這真的幫助我瞭解這裏的情況。謝謝埃裏克! – qodeninja