2011-10-27 51 views
1

我写这个小程序来匹配模式和替代它:错误模式识别与字符串匹配的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

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

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

阐述:

你未使用严格和警告,这是一个坏主意。建议使用三参数的开放和词法文件句柄,并且我建议在你的死信息中使用$!,这样你就知道它为什么会失败。我还调整了你的另一个分割来消除空白并限制到两个字段(因为从来没有两个以上的队伍)。

如果您不打算使用它,则不需要$dummy变量,因为拆分中的其他值将被丢弃。然而,你需要为换行符进行调整,否则你有时会得到两个。我加了chomp

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

print join "\t", $hour, $match, $odd1, $oddx, $odd2 . "\n"; 

代码:

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]; 
} 
3

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

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

我认为这将明确说明问题所在。