perl程序中的模式识别和字符串匹配错误

时间:2011-10-27 10:50:04

标签: perl

我已经编写了这个小程序来匹配模式并替换它:

#!/usr/bin/perl
$LOGFILE = "odds.dat";
open(LOGFILE) or die("Could not open log file.");
foreach $line (<LOGFILE>) {
($hour, $match, $odd1, $oddx, $odd2, $dummy) = split(/\,/,$line);
($hteam,$ateam) = split(/ § /,$match);
$hteam=get_name($hteam);
$ateam=get_name($ateam);
$match="$hteam - $ateam";
$foo=qq("$hour" "$match" $odd1 $oddx $odd2 \n) ;
print $foo;
               }
sub get_name {
# Return the full name for the team, if it exists, otherwise return the original
my %alias = (
"Atletico-MG" => "Atletico Mineiro",
"Atletico-PR" => "Atletico Paranaense",
...
...
"U.A.N.L.- Tigres" => "U.A.N.L.",
...
...
 );
return $alias{$_[0]} // $_[0];
}  

其中odds.dat是:

2011-10-28 20:00 , Atletico-MG § Atletico-PR ,2.00 ,5.00, 6.00
2011-10-28 20:00 ,U.A.N.L.- Tigres § Atletico-MG ,2.00,5.00,6.00

但输出是:

"2011-10-28 21:15 " " Atletico-MG - Atletico-PR " 2.00  5.00  6.00
"2011-10-28" "U.A.N.L. - Atletico-MG " 2.00 5.00 6.00

为什么不识别Atletico-MG和Atletico-PR?

2 个答案:

答案 0 :(得分:3)

将以下调试行添加到get_name函数的顶部。

warn "In get_name looking for <$_[0]>\n";

我认为这会清楚问题是什么。

答案 1 :(得分:2)

您的团队名称中有空格,例如" Atletico-MG""Atletico-MG"不符。这可以在第一次拆分中删除。您也不需要转义逗号:

split(/\s*,\s*/,$line);

<强>精化:

你没有使用严格和警告,这是一个坏主意。建议使用三参数open和lexical文件句柄,我建议在你的die消息中使用$!,这样你才知道它失败的原因。我还调整了你的其他分割来剥离空白并限制为两个字段(因为从来没有超过两个团队)。

如果您不打算使用$dummy变量,则不需要chomp变量,因为拆分中的其他值将被丢弃。但是,您需要调整换行符,否则有时会得到两行。我添加了print join "\t", $hour, $match, $odd1, $oddx, $odd2 . "\n";

我假设您的双引号时间和团队名称都是故意的。您可以考虑使用制表符分隔符进行打印。它具有相当的可读性,并且在进一步处理时也使分割更容易。 E.g:

use strict;
use warnings;

my $logfile = "odds.dat";
open my $log, '<', $logfile or die "Could not open log file: $!";
foreach my $line (<$log>) {
    chomp $line;
    my ($hour, $match, $odd1, $oddx, $odd2) =
        split /\s*,\s*/, $line;
    my ($hteam,$ateam) = split /\s*§\s*/, $match, 2;
    $hteam=get_name($hteam);
    $ateam=get_name($ateam);
    $match = "$hteam - $ateam";
    print qq("$hour" "$match" $odd1 $oddx $odd2\n);
}
sub get_name {
# Return the full name for the team, if it exists,
# otherwise return the original
    my %alias = (
        "Atletico-MG" => "Atletico Mineiro",
        "Atletico-PR" => "Atletico Paranaense",
        "U.A.N.L.- Tigres" => "U.A.N.L.",
    );
    return $alias{$_[0]} // $_[0];
}  

<强>代码:

{{1}}