我似乎无法创建一个对该类是全局的变量,并且可以在该类的所有子例程中使用。
我看到各种各样的例子显然有效,但我无法做任何工作。
代码:
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.
这里发生了什么?
答案 0 :(得分:5)
虽然在执行任何代码之前将编译整个代码,但可执行部分按顺序发生。特别是,new()调用发生在包Player中的任何赋值或const调用之前。
将所有播放器代码移动到Player.pm文件并使用use Player;
调用它将导致它在新的之前立即编译并执行并按预期工作。
答案 1 :(得分: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;
。