很抱歉有一个非常基本的问题,但我是Perl的初学者级别,无法在SO(或其他任何地方!)上找到适合此问题的解释。我知道我可以写一些例子并尝试解读这个例子但我真的可以使用专家的一些知识。
我正在浏览开发人员使用以下代码来源代码的代码:
use libExample qw(:const)
根据我的理解,这意味着从libExample中获取常量,但我们真的想知道它是如何工作的。
为什么我不能简单地说:use libExample qw(const)
(试图了解:
)
我们可以/应该在libExample.pm
本身写一些东西,让其他开发人员利用这个库来代替const来提及这些选项。
谢谢!
答案 0 :(得分:8)
The syntax use Foo qw(:const)
is using the EXPORT_TAGS feature in Exporter.
When you set up your library module, you usually have a bunch of functions or class variables. Then you configure Exporter by telling it what to export by default
package Foo;
use Exporter;
our @EXPORT = qw( frobnicate );
sub frobnicate { ... }
or when they are asked for.
OUR @EXPORT_OK = qw( frobnicate barnicate );
sub barnicate { ... }
But you can also tell it to group things together, so the user of your library does not need to list all the methods. Consider this example.
package Foo;
use Exporter;
our @EXPORT_OK qw(monday tuesday wednesday thursday friday saturday sunday);
sub monday { ... }
sub tuesday { ... }
sub wednesday { ... }
sub thursday { ... }
sub friday { ... }
sub saturday { ... }
sub sunday { ... }
Now if I wanted all the working days, I'd have to do this:
use Foo qw(monday tuesday wednesday thursday friday);
That's one long line. Instead, it would be super useful if those could be grouped. Well, they can be. If you do this instead in your library:
package Foo;
use Exporter;
our %EXPORT_TAGS = (
working_days => [
qw(monday tuesday wednesday thursday friday)
],
weekend_days => [
qw(saturday sunday)
]
);
# ...
We can then use it with one tag instead of five function names:
use Foo qw(:working_days);
Note that this is equivalent:
use Foo ':working_days';
答案 1 :(得分:6)
use libExample qw(:const)
will pick all names in $EXPORT_TAGS{const}
anonymous array and will import them to current namespace.
Whereas
use libExample qw(const)
will pick const and will import it in current namespace.
There are also other variants:
[!]name This name only
[!]:DEFAULT All names in @EXPORT
[!]:tag All names in $EXPORT_TAGS{tag} anonymous array
[!]/pattern/ All names in @EXPORT and @EXPORT_OK which match
Please go through Exporter documentation for more details on the topic.