如何“使用"一个“使用"的多个模块? [英] How to "use" multiple modules with one "use"?
问题描述
我想在所有程序中使用一些软件包和一些编译指示,例如:
I want use some packages and some pragmas in all my programs, like:
use 5.014;
use warnings;
use autodie;
use My::ModuleA::Something;
use ModuleB qw(Func1 Func2);
我不想在每个模块中重复我自己,所以寻找一种方法来制作一个包装,例如My::Common
将包含上述软件包的内容以及在我的程序中仅执行以下操作:
I don't want repeat myself in every module, so looking for a way how to make one package e.g. My::Common
what will contain the above packages and in my programs do only:
use My::Common;
say Func1("hello"); #say enabled and Func1 imported in the My::Common
如何实现?
读为preldoc -f use
和perldoc perlmodlib
,所以我想我必须有点"用BEGIN加上require& import来做到这一点,但绝对不知道如何.
The was read preldoc -f use
and perldoc perlmodlib
so i think I must "somewhat" to do this with BEGIN plus require&import, but absolutely don't know how.
更新:我已经尝试了基本的操作.
UPDATE: I'm already tried the basic things.
使用require
-我的prg.pl程序.
With require
- my prg.pl program.
require 'mymods.pl';
$var = "hello";
croak "$var\n";
mymods.pl包含
mymods.pl contain
use strict;
use feature 'say';
use Carp qw(carp croak cluck);
1;
不起作用.出现错误:
$ perl prg.pl
String found where operator expected at prg.pl line 3, near "croak "$var\n""
(Do you need to predeclare croak?)
syntax error at prg.pl line 3, near "croak "$var\n""
Execution of prg.pl aborted due to compilation errors.
带有使用我的":
with "use My":
use My;
$var = "hello";
croak "$var\n";
我的My.pm
package My;
use strict;
use feature 'say';
use Carp qw(carp croak cluck);
1;
也不起作用.遇到相同的错误.
DOES NOT WORKS either. Got the same error.
任何可行的主意吗?
推荐答案
我会这样做:
package My::Common;
use 5.14.0;
use strict;
use warnings;
use autodie;
use Carp qw(carp croak cluck);
sub import {
my $caller = caller;
feature->import(':5.14');
# feature->import('say');
strict->import;
warnings->import;
## autodie->import; # <-- Won't affect the caller side - see my edit.
{
no strict 'refs';
for my $method (qw/carp croak cluck/) {
*{"$caller\::$method"} = __PACKAGE__->can($method);
}
}
}
1;
如果我错了,请纠正我,否则会有更好的方法.
Please correct me if I'm wrong, or there's a better way.
编辑:
对不起,我在使用autodie->import
...
Sorry, I was wrong in using autodie->import
...
这应该可以,但是它假定您总是从main
包中调用My::Common
:
This one should work, but it assumes that you always call My::Common
from the main
package:
package My::Common;
# ...
sub import {
# ...
strict->import;
warnings->import;
{
package main;
autodie->import;
}
# ...
}
因此,当然,向每个脚本中添加use autodie;
更加安全和简单:
So, of course, it's much safer and simpler to add a use autodie;
to each script:
use My::Common;
use autodie;
# ...
这篇关于如何“使用"一个“使用"的多个模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!