我似乎無法創建一個變量,該變量是該類的全局變量,並且可用於該類的所有子例程。Perl類變量
我看遍了那些顯然工作的例子,但我無法得到任何工作。
代碼:
my $test = new Player(8470598);
package Player;
use strict;
use warnings;
use Const::Fast;
$Player::URL = 'asdfasdasURL';
my $test3 = '33333333';
our $test4 = '44444444444';
const $Player::test0 => 'asdfasdas000';
const my $test1 => 'asdfasdas111';
const our $test2 => 'asdfasdas222';
sub new{
print $Player::URL;
print $Player::test0;
print $test1;
print $test2;
print $test3;
print $test4;
return(bless({}, shift));
}
輸出:
Use of uninitialized value $Player::URL in print at D:\Text\Programming\Hockey\test.pl line 19.
Use of uninitialized value $Player::test0 in print at D:\Text\Programming\Hockey\test.pl line 20.
Use of uninitialized value $test1 in print at D:\Text\Programming\Hockey\test.pl line 21.
Use of uninitialized value $Player::test2 in print at D:\Text\Programming\Hockey\test.pl line 22.
Use of uninitialized value $test3 in print at D:\Text\Programming\Hockey\test.pl line 23.
Use of uninitialized value $Player::test4 in print at D:\Text\Programming\Hockey\test.pl line 24.
這到底是怎麼回事?
另一種方法是初始化(但不聲明)INIT或BEGIN塊內的變量。 – amon 2013-02-17 17:04:29
OH,似乎已經修復它。這是一個奇怪的執行順序。 所以在執行到類之前,類變量不會被執行。這是錯誤的行爲,對嗎? Perl應該在開始正常執行之前執行包中的空閒代碼,對吧?能夠在該類甚至完全創建之前調用類中的方法就很奇怪。 – Jonathon 2013-02-17 17:21:25
您可以通過將代碼移動到單獨的文件並使用它,或將其封裝在BEGIN塊中來實現。代碼不是真的「在」一個包中;所有的package語句所做的就是將任何未限定的標識符的默認包從該點更改爲下一個包或封閉塊或文件的末尾(並且更改'__PACKAGE__'和'SUPER ::'引用的內容) – ysth 2013-02-17 17:29:48