0
package A;
$ENV{MOJO_USERAGENT_DEBUG} =1;
use Test::Mojo;
use utf8;

....
;
1;
package B;
BEGIN{ $ENV{MOJO_USERAGENT_DEBUG =1 } };
use Test::Mojo;
use utf8;
...
;
1;

Test::Mojo导入Mojo::UserAgent模块:

package Test::Mojo;
...
use Mojo::UserAgent;
...
1;

为什么包 A 中的代码无法打开调试。但是包B可以吗?

4

2 回答 2

3

因为 Test::Mojo 在加载时会检查变量,所以您需要在此之前设置环境。

于 2013-03-17T09:59:13.260 回答
2
#!/usr/bin/env perl
# vim:set shiftwidth=4 tabstop=4 expandtab ai smartindent fileformat=unix fileencoding=utf-8 syntax=perl:
# http://perldoc.perl.org/perlmod.html#BEGIN,-UNITCHECK,-CHECK,-INIT-and-END
package init;
            { print "10. Ordinary code runs at runtime.\n"; }
END         { print "16. So this is the end of the tale.\n" }
INIT        { print " 7. INIT blocks run FIFO just before runtime.\n" }
UNITCHECK   { print " 4. And therefore before any CHECK blocks.\n" }
CHECK       { print " 6. So this is the sixth line.\n" }
            { print "11. It runs in order, of course.\n"; }
BEGIN       { print " 1. BEGIN blocks run FIFO during compilation.\n" }
END         { print "15. Read perlmod for the rest of the story.\n" }
CHECK       { print " 5. CHECK blocks run LIFO after all compilation.\n" }
INIT        { print " 8. Run this again, using Perl's -c switch.\n" }
            { print "12. This is anti-obfuscated code.\n"; }
END         { print "14. END blocks run LIFO at quitting time.\n" }
BEGIN       { print " 2. So this line comes out second.\n" }
UNITCHECK   { print " 3. UNITCHECK blocks run LIFO after each file is compiled.\n" }
INIT        { print " 9. You'll see the difference right away.\n" }
            { print "13. It merely _looks_ like it should be confusing.\n"; }
sub import {
    print "IMPORT\n";
}
1;

这应该很清楚;-)。

换句话说:BEGIN 块和“使用”语句在同一编译步骤中按照它们出现的顺序进行评估。在两个示例中,BEGIN 和“use”已经互换,因此在 A 中,BEGIN 块在“use Test::Mojo”之后执行。我的猜测是 Test::Mojo 在编译时评估 env var。如果它会在运行时评估它,它应该可以工作。

更多细节?看这里

于 2013-03-17T19:46:09.820 回答