【问题标题】:Pattern matching while reading from the files using Perl使用 Perl 从文件中读取时的模式匹配
【发布时间】: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


【解决方案1】:

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

也许是这样的? 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

【讨论】:

    猜你喜欢
    • 2016-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多