使用Perl从文件读取时的模式匹配

时间:2015-04-09 19:19:23

标签: perl pattern-matching

我在阅读文件并匹配模式时遇到了问题

文件内容

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

1 个答案:

答案 0 :(得分:0)

我建议您将选项文件读入数组,这样就不需要打开和读取两次

也许这样的事情? if $input =~ /(\d+)/中的正则表达式从输入中提取任意数字,因此无需删除空格或换行符,而and $menu[$1]检查菜单中是否存在此类数字

use strict; 
use warnings; 

my $conf_file = 'conf_file.txt';

my @menu;
{
  open my $fh, '<', $conf_file or die qq{Unable to open "$conf_file" for input: $!};
  while ( <$fh> ) {
    if ( /(\d+)\s*:\s*(.*\S)/ ) {
      $menu[$1] = $2;
      print;
    }
  }
}

my $option;
until ( $option) {
  print "Please choose a number from the list above: ";
  my $input = <STDIN>;
  $option = $1 if $input =~ /(\d+)/ and $menu[$1];
}

print "Your Choice was: $option\n";
print "Corresponding to $menu[$option]\n";

<强>输出

E:\Perl\source>conf_file.pl
1: Recturing Svc
2: Finance
9: Payments
19: Mobile
29: Bankers
Please choose a number from the list above: 3
Please choose a number from the list above: 9
Your Choice was: 9
Corresponding to Payments