Perl 模式匹配数组
我想将我读取的字符串与可能匹配的数组进行匹配。如果它可以返回匹配字符串的索引也很好。我可以很容易地进行硬编码......这次可能会为了方便起见,但对于一般情况,我想看看这是否可能。我浏览了一些书籍和在线(包括 stackoverflow),但找不到我要找的东西,也无法完全连接这些点来弄清楚自己。
这是我正在寻找的一般事物的示例......当然它不起作用,这就是我寻求帮助的原因。但我希望这足以推断我的意图。
例子:
my $patterns;
my $line;
my $c = 0 ;
$patterns{$c++} = "$exact" ; # where the $ in $exact marks the beginning of line.
$patterns{$c++} = "$T?:" ; # where the ? is the normal wildcard
$patterns{$c++} = "" ;
$patterns{$c++} = "exact" ;
open (FILE, "example.txt") || die "Unable to open file.\n";
while (my $line = <IN>) {
my $idx = -1;
for ($i=0; $i<$c :$i++) {
if ($line =~ /$patterns{$i}/ ) { $idx = $i ; }
}
$result = $idx; # of course this will return index of last pattern match, but that's ok
}
close(FILE);
I want to match a string I read against an array of possible matches. Would also be good if it could return the index of the match string. I COULD hard code easily enough ... and probably will for expediency this time around, but for general case, I'd like to see if this is possible. I've looked through some books and online (including stackoverflow), but can't find what I'm looking for and can't quite connect the dots to figure it out myself.
Here's an example of the general kind of thing I'm looking for ... of course it does not work, which is why I am asking for help. But I hope it is sufficient to infer my intent.
Example:
my $patterns;
my $line;
my $c = 0 ;
$patterns{$c++} = "$exact" ; # where the $ in $exact marks the beginning of line.
$patterns{$c++} = "$T?:" ; # where the ? is the normal wildcard
$patterns{$c++} = "" ;
$patterns{$c++} = "exact" ;
open (FILE, "example.txt") || die "Unable to open file.\n";
while (my $line = <IN>) {
my $idx = -1;
for ($i=0; $i<$c :$i++) {
if ($line =~ /$patterns{$i}/ ) { $idx = $i ; }
}
$result = $idx; # of course this will return index of last pattern match, but that's ok
}
close(FILE);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在不确切知道您要寻找什么的情况下,这就是您的代码转换为实际 Perl 代码的情况。
Without knowing exactly what you are looking for, this is your code transformed into actual Perl code.
或者,如果您使用的是 perl 5.8 而不是 5.10,Regexp::Assemble将为您处理这个问题:
R::A 还可以设置为告诉您哪些原始模式匹配,我不认为这是 5.10 智能匹配运算符(
~~) 可以,但这会给你实际的模式 (
exact
) 而不是它的索引 (3)。如果您确实需要索引,则需要按顺序循环测试每个模式(如果您有许多模式,这可能会对性能产生重大影响),或者构建一个pattern =>; index
哈希并使用它来查找匹配模式的索引。Alternately, if you're using perl 5.8 rather than 5.10, Regexp::Assemble will handle this for you:
R::A can also be set to tell you which of the original patterns matched, which I don't think the 5.10 smart match operator (
~~
) can do, but that will give you the actual pattern (exact
) rather than its index (3). If you really need the index, you'll either need to loop over the patterns testing each in order (which is likely to have a significant performance impact if you have many patterns) or build apattern => index
hash and use that to look up the index of the matched pattern.