1

我似乎无法创建一个对该类全局且可用于该类的所有子例程的变量。

我看到了所有明显有效的例子,但我无法得到任何我做的工作。

代码:

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.

这里发生了什么?

4

2 回答 2

5

虽然整个代码将在执行之前编译,但可执行部分按顺序发生。特别是,您的 new() 调用发生在 Player 包中的任何分配或 const 调用之前。

将所有 Player 代码移动到 Player.pm 文件并调用它use Player;会导致它在 new 之前立即编译和执行,并按预期工作。

于 2013-02-17T16:58:47.907 回答
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;
于 2013-02-17T21:35:53.767 回答