0

我使用 smartmatch 来检查字符串是否匹配正则表达式模式。在我决定将正则表达式存储在文本文件中后,它停止工作。

my $str   = '123456, some text.';
my $regex = qr/^\d+, some text\.$/;
print "Regex: $regex\n";

此时,打印的正则表达式为(?^:^\d+, some text\.$). 我将它复制粘贴到一个文件中,然后让代码读取文件并检索存储在$regexFromFile.

以下行证实了这一点$regex并且$regexFromFile是相同的,然后我继续以$str各种方式对正则表达式进行测试。

print 'Is regex equal to regexFromFile? ' . ($regex eq $regexFromFile) . "\n";

print 'Does str match regex         using =~ ? ' . ($str =~ $regex)         . "\n";
print 'Does str match regexFromFile using =~ ? ' . ($str =~ $regexFromFile) . "\n";
print 'Does str match regex         using ~~ ? ' . ($str ~~ $regex)         . "\n";
print 'Does str match regexFromFile using ~~ ? ' . ($str ~~ $regexFromFile) . "\n";

该代码的最后一行与前三行的行为​​不同。

这是代码的完整输出:

Regex: (?^:^\d+, some text\.$)
Is regex equal to regexFromFile? 1
Does str match regex         using =~ ? 1
Does str match regexFromFile using =~ ? 1
Does str match regex         using ~~ ? 1
Does str match regexFromFile using ~~ ? 

(注意1末尾没有。)

编辑:要回答评论,这里是文件的读取方式。

open(my $FILEHANDLE, 'file.txt') or die "Error: Could not open file.\n";
my @content = <$FILEHANDLE>;
close($FILEHANDLE) or print "Could not close file.\n";
my @content_woEol = ();
foreach my $line (@content){
    $line =~ s/\s*$//;
    push(@content_woEol, $line);
}
my $regexFromFile = $content_woEol[0];
4

3 回答 3

4

智能匹配被破坏。请避免使用它。[1]

$str是一个字符串,并且$regexFromFile是一个字符串,所以$str ~~ $regexFromFile等价于$str eq $regexFromFile.

如果您想$str ~~ $regexFromFile等效于$str =~ $regexFromFile,则必须将错误名称$regexFromFile从字符串转换为正则表达式(例如使用qr//)。当然,更好的解决方案是简单地使用=~.


  1. 许多年前,它被作为一种弃用形式进行了实验,因此可以修复它。继续使用这个损坏的功能实际上阻止了最近修复它的努力。
于 2018-03-01T15:38:26.610 回答
2

的结果qr//实际上是一个预编译的正则表达式。正如您所做的那样,将打印的正则表达式复制粘贴到文件中,然后从文件中读取它,这不是问题。如果您直接在代码中编写此行,您将遇到相同的行为:

my $regexFromFile = '(?^:^\d+, some text\.$)';

如果您想在这里使用 smatmatch,我建议您执行以下操作:

my $str   = '123456, some text.';
my $regex = '^\d+, some text\.$';

# Manually store this in the file: ^\d+, some text\.$
# Read $regexFromFile from the file

print 'Does str match regex         using =~ ? ' . ($str =~ /$regex/)         . "\n";
print 'Does str match regexFromFile using =~ ? ' . ($str =~ /$regexFromFile/) . "\n";
print 'Does str match regex         using ~~ ? ' . ($str ~~ /$regex/)         . "\n";
print 'Does str match regexFromFile using ~~ ? ' . ($str ~~ /$regexFromFile/) . "\n";

注意额外的/.../. 输出:

Does str match regex         using =~ ? 1
Does str match regexFromFile using =~ ? 1
Does str match regex         using ~~ ? 1
Does str match regexFromFile using ~~ ? 1
于 2018-03-02T23:53:47.843 回答
-1

Smartmatch自 v5.18 以来一直是实验性的,不应该在现场制作软件中使用

它一直需要

use feature 'switch';

除非你是一个有意识或明确无视警告的人,否则

no warnings qw/ experimental::smartmatch /;

那么你就会对它的消亡有充分的警告

你做出了明智的选择,从一开始就明显错误

于 2018-03-01T14:58:26.953 回答