【发布时间】:2015-04-09 19:19:22
【问题描述】:
我在读取文件并匹配模式时遇到问题
文件内容
1: Recturing Svc
2: Finance
:
:
9: Payments
:
:
19: Mobile
:
:
29: Bankers
我的代码如下所示
open(INPUTFILE, "<$conf_file") or die("unable to open text file");
foreach (<INPUTFILE>) {
print "$_";
}
close INPUTFILE;
print "Please choose a number from the list above: ";
chop($input = <STDIN>);
$input = trim($input);
print "Your Choice was: $input\n";
$TEMP = "$input:";
open(INPUTFILE, "<$conf_file") or die("unable to open text file for comparision");
foreach $line (<INPUTFILE>) {
if ($line =~ /$TEMP/) {
print " exact match: $& \n";
print " after match: $' \n";
$svc = $';
print "ServiceL $svc \n";
}
}
close INPUTFILE;
当我选择时,它匹配多个项目,例如 9: 和 19: 和 29:。例如,如果我输入 9 那么它会打印出来
9: Payments
19: Mobile
29: Bankers
【问题讨论】:
-
尝试
if($line =~ /^$TEMP:/) {仅匹配行首并与后面的:匹配 -
我可以添加 /^$TEMP/ 之类的东西,但这会在 90 处中断。
-
是的,因为您必须包含
:- 因为您肯定知道该数字后跟一个冒号。所以你想搜索/^9:/而不是/^9/
标签: perl pattern-matching