2013-02-17 49 views
1

我似乎無法創建一個變量,該變量是該類的全局變量,並且可用於該類的所有子例程。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. 

這到底是怎麼回事?

回答

5

雖然在執行任何代碼之前將編譯整個代碼,但可執行部分按順序發生。特別是,您的new()調用發生在Package中的任何賦值或常量調用之前。

移動所有的播放器代碼到Player.pm文件,並use Player;調用它會導致它被立即編譯和新工作之前,執行如您所願。

+0

另一種方法是初始化(但不聲明)INIT或BEGIN塊內的變量。 – amon 2013-02-17 17:04:29

+0

OH,似乎已經修復它。這是一個奇怪的執行順序。 所以在執行到類之前,類變量不會被執行。這是錯誤的行爲,對嗎? Perl應該在開始正常執行之前執行包中的空閒代碼,對吧?能夠在該類甚至完全創建之前調用類中的方法就很奇怪。 – Jonathon 2013-02-17 17:21:25

+1

您可以通過將代碼移動到單獨的文件並使用它,或將其封裝在BEGIN塊中來實現。代碼不是真的「在」一個包中;所有的package語句所做的就是將任何未限定的標識符的默認包從該點更改爲下一個包或封閉塊或文件的末尾(並且更改'__PACKAGE__'和'SUPER ::'引用的內容) – ysth 2013-02-17 17:29:48

0

包級代碼

my $test = new Player(8470598); 

正在前,包級代碼

$Player::URL = 'asdfasdasURL'; 
my $test3 = '33333333'; 
our $test4 = '44444444444'; 
const $Player::test0 => 'asdfasdas000'; 
const my $test1 => 'asdfasdas111'; 
const our $test2 => 'asdfasdas222'; 

,因爲它早在文件中來執行。

如果你想內聯包,改變

use Player; 

BEGIN { 
    package Player; 

    ... 

    $INC{"Player.pm"} = 1; 
} 

use Player; 
my $test = Player->new(8470598); 

你有時可以走捷徑。在這種情況下,您可以同時剪切:

  • BEGIN是不需要的。
  • $INC{"Player.pm"} = 1;可以通過丟棄use Player;來刪除。