regex - 如何从模块中导出正则表达式

标签 regex perl

我有一个希望从我的模块中导出的正则表达式,代码如下:

package regExport;
use strict;
use warnings;
use Exporter qw(import);
our @EXPORT_OK = qw(re);

my re = /.../; # my regex is here

它被导入这里

use regExport qw(re);
my @li = ("man", "qwrt", "mnbv", "azx", "aeiou");

foreach my $st (@li) {
     $li =~ a/b/; # I wish to test my regex on each of these strings
}

任何人都知道我将如何去做。我对如何去做这件事感到相当困惑。

最佳答案

最简单但不是最好的方法(见下文)是使用模式创建变量。最佳使用qr operator为此,然后可以导出变量

package RegExport;

use strict;
use warnings;

use Exporter qw(import);
our @EXPORT_OK = qw($re_pattern);

our $re_pattern = qr/(\w+)/i;  # capture a "word" case-insensitive

1;

请注意,我已将包名大写,这符合 Perl 的 Pascal 大小写惯例。 (那么文件名需要跟在后面,是RegExport.pm。)

然后将其用作

use warnings;
use strict;
use feature 'say';

use FindBin qw($RealBin);
use lib $RealBin;

use RegExport qw($re_pattern);

my $text = q(Some text with a bunch of words. In sentences.);

while ($text =~ /$re_pattern/g) { 
    say "Word: $1";
}

我希望 RegExport.pm 与程序位于同一目录中。使用$RealBin将相对于程序本身所在位置的目录(在本例中为程序所在的目录)添加到包含库的搜索路径中是一种好方法。

如果您真的想使用这样的变量(但请继续阅读!),则无需从其包中导出它,但可以在调用者中使用其完全限定名称

use RegExport;

... $RegExport::re_pattern ...

这是有时在库中针对各种设置所做的。

但是,文档在 What not to export 部分对此有一些说明。

Do not export variable names.

@EXPORT_OK = qw($svar @avar %hvar); # DON'T!

Exporting variables is not a good idea. They can change under the hood, provoking horrible effects at-a-distance that are too hard to track and to fix. Trust me: they are not worth it.

这个好建议偶尔在图书馆被违反,效果很好;一个例子是上面使用的 $RealBin。但如果你没有压倒一切的理由,那么最好遵循它——并使用函数返回值

package RegExport;

use strict;
use warnings;

use Exporter qw(import);
our @EXPORT_OK = qw(get_pattern);

sub get_pattern {
    my @specs = @_;  # any input on how to form the pattern

    my $re_pattern = qr{...};

    return $re_pattern;
}

1;

现在你把它当作

use RegExport qw(get_pattern);

my $re = get_pattern();   # or pass extra rules for how to form it

并在正则表达式中使用 $re 作为就绪模式。

现在这段代码的用户和 future 的代码维护者都很高兴。

关于regex - 如何从模块中导出正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69856552/

相关文章:

javascript - js 获取直到前 N 位的子字符串

perl - 如何在 mod_perl2 下运行 Devel::Cover?

node.js - 如何正则表达式将使用 "++++"、 "+++"作为组分隔符的文本输入文件转换为 CSV 或 JSON

php - 在 php 中使用正则表达式过滤 URL

perl - 在 Perl 中打开超过 10,000 个文件的问题

perl - 编写 Perl CGI 应用程序的最佳方法是什么?

Perl:如何在没有警告的情况下调用 END {} 中的对象方法?

json - 脚本可以很好地提取和打印 UTF-8 单词,但将 JSON 打印为垃圾

python - 如何使用正向后行断言从单词 "named"之后的字符串中提取子字符串

java - 正则表达式删除java中的特殊字符