在使用 perl 包时将参数传递给它 [英] Passing arguments to a perl package while using it
问题描述
如何在使用包时传递一些参数,例如:
How to pass some arguments while using a package, for example:
use Test::More tests => 21;
我找不到有关此功能的任何有价值的文档.传递这样的论点有什么利弊吗?
I wasn't able to find any valuable documentation about this featue. Are there any pros and cons of passing such arguments?
推荐答案
useMy::Module LIST
做了两件事:1) 它 require
s My::Module
;和 2) 调用 My::Module->import(LIST)
.
use My::Module LIST
does two things: 1) It require
s My::Module
; and 2) Invokes My::Module->import(LIST)
.
因此,您可以编写模块的 import
例程来处理以您想要的任何方式传递的参数列表.如果您确实正在编写一个不向调用者的命名空间导出任何内容的面向对象的模块,这将变得更加容易.
Therefore, you can write your module's import
routine to treat the list of arguments passed any which way you want. This becomes even easier if you are indeed writing an object oriented module that does not export anything to the caller's namespace.
这是一个毫无意义的例子:
Here's a rather pointless example:
package Ex;
use strict;
use warnings;
{
my $hello = 'Hello';
sub import {
my $self = shift;
my $lang = shift || 'English';
if ($lang eq 'Turkish') {
$hello = 'Merhaba';
}
else {
$hello = 'Hello';
}
return;
}
sub say_hello {
my $self = shift;
my $name = shift;
print "$hello $name!\n";
return;
}
}
__PACKAGE__;
__END__
以及使用它的脚本:
#!/usr/bin/env perl
use strict;
use warnings;
use Ex 'Turkish';
Ex->say_hello('Perl');
Ex->import;
Ex->say_hello('Perl');
输出:
$ ./imp.pl
Merhaba Perl!
Hello Perl!
这篇关于在使用 perl 包时将参数传递给它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!