使用它时将参数传递给 perl 包
Passing arguments to a perl package while using it
如何在使用包时传递一些参数,例如:
use Test::More tests => 21;
我找不到关于此功能的任何有价值的文档。通过这样的论点有什么利弊吗?
有人说在某些场景下可读性更好,但本质上和
是一样的
use Test::More qw(tests 21);
(test
由粗逗号 =>
自动引用,数字不需要引用)。
主要缺点是您不能使用 Exporter
中的默认 import
子例程,它只需要将符号列表(或表示符号集合的标签)导入调用包裹
Test::More
inherits a custom import
routine from the superclass Test::Builder::Module
,它使用 use
语句中提供的参数来配置测试计划。它还反过来使用 Exporter
来处理指定的选项,如 import => [qw/ symbols to import /]
如果您有特定要求,自定义 import
子例程几乎可以完成任何事情,但偏离标准的面向对象语义太远可能是不明智的
use My::Module LIST
does two things: 1) It require
s My::Module
; and 2) Invokes My::Module->import(LIST)
.
因此,您可以编写模块的 import
例程来处理以任何方式传递的参数列表。如果您确实在编写一个不向调用者的命名空间导出任何内容的面向对象模块,这将变得更加容易。
这是一个毫无意义的例子:
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!
如何在使用包时传递一些参数,例如:
use Test::More tests => 21;
我找不到关于此功能的任何有价值的文档。通过这样的论点有什么利弊吗?
有人说在某些场景下可读性更好,但本质上和
是一样的use Test::More qw(tests 21);
(test
由粗逗号 =>
自动引用,数字不需要引用)。
主要缺点是您不能使用 Exporter
中的默认 import
子例程,它只需要将符号列表(或表示符号集合的标签)导入调用包裹
Test::More
inherits a custom import
routine from the superclass Test::Builder::Module
,它使用 use
语句中提供的参数来配置测试计划。它还反过来使用 Exporter
来处理指定的选项,如 import => [qw/ symbols to import /]
如果您有特定要求,自定义 import
子例程几乎可以完成任何事情,但偏离标准的面向对象语义太远可能是不明智的
use My::Module LIST
does two things: 1) It require
s My::Module
; and 2) Invokes My::Module->import(LIST)
.
因此,您可以编写模块的 import
例程来处理以任何方式传递的参数列表。如果您确实在编写一个不向调用者的命名空间导出任何内容的面向对象模块,这将变得更加容易。
这是一个毫无意义的例子:
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!