聘我网

新概念招聘3.0

为何补集修饰符(/c)在match模式不工作?

vote up0vote downstar

参照

$pathname =˜ tr/a-zA-Z/_/cs; # change non-(ASCII)alphas to single underbar

我以为"abc" =~ /\Aabc\z/gc应该是false

结果却发现其为true

点解?

 

1 个答复

vote up0vote downcheck

/c对于trm的作用是不同的:

$pathname =˜ tr/a-zA-Z/_/cs; # change non-(ASCII)alphas to single underbar

"abc" =~ /\Aabc\z/gc;# c avoids position reset

tr等价于

y/SEARCHLIST/REPLACEMENTLIST/cds

这里a-zA-Z并不是regex,只是SEARCHLIST

同样这里的/c表示Complement the SEARCHLIST

再说下/gc修饰符对于regex的作用

perlre描述如下:

g and c Global matching, and keep the Current position after failed matching. Unlike i, m, s and x, these two flags affect the way the regex is used rather than the regex itself. See Using regular expressions in Perl in perlretut for further explanation of the g and c modifiers.

即对于m/c使得在匹配失败时pos不被重置为undef

看个例子:

#!/usr/bin/perl

use strict;
use warnings;

my $s = "abc";
pos $s = 0;
study $s;
$s =~ /a/gc;
$s =~ /"d"/gc;
print pos $s;

输出:

1

#!/usr/bin/perl

use strict;
use warnings;

my $s = "abc";
pos $s = 0;
study $s;
$s =~ /a/gc;
$s =~ /"d"/g;
print pos $s;

输出:

Use of uninitialized value in print at oh line 11.

背景知识

关于前面说的pos

指的是匹配首末字符的offset信息,

保存在@-/@+这两个数组中

#!/usr/bin/perl

use strict;
use warnings;

my $s = "abc";
pos $s = 0;
study $s;
$s =~ /a/gc;
print "The entire match began at $-[0] and ended at $+[0]\n";
=anything
print "The first match began at $-[1] and ended at $+[1]\n";
print "The second match began at $-[2] and ended at $+[2]\n";
=cut

输出:

The entire match began at 0 and ended at 1
链接

您的回答





不是您要找的问题? 浏览其他含有标签 的问题或者 自己问个.