elb*_*laf 0 arrays perl design-patterns
我想匹配我读取的字符串与可能的匹配数组.如果它可以返回匹配字符串的索引也会很好.我可以很容易地编写硬编码......这次可能是为了权宜之计,但对于一般情况,我想看看这是否可行.我已经浏览了一些书籍和在线(包括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);
Run Code Online (Sandbox Code Playgroud)
Bra*_*ert 10
在不确切知道您要查找的内容的情况下,这是您的代码转换为实际的 Perl代码.
use warnings;
use strict;
use autodie; # open and close will now die on failure
use 5.10.1;
my @patterns = (
qr"^exact",
qr"^T.?:",
"",
"exact",
);
my $result;
open my $fh, '<', 'example.txt';
while ( my $line = <$fh> ) {
chomp $line;
$result = $line ~~ @patterns;
}
close($fh);
Run Code Online (Sandbox Code Playgroud)