2012-02-29 82 views
0

假设我有两个文件,格式如下。Perl:用另一个文件给出的格式匹配一个文件

文件1:

username <username> 
password <password1> 
password <password2> 
hello world 

文件2:

username hello 
password test 
password testing 
hello world 
good luck 

我希望能够检查文件2遵循相同的格式文件1。这意味着如果具有以下格式的文件,将无法通过我的测试。

BADFILE:

username hello 
password test 
hello world 

必须有与 “密码” 开始正好2行。目前,我的程序能够检查是否有以“用户名”和“密码”开头的行。我似乎无法检查,如果File1具有重复的行与“密码”相同的起始字,它还应该检查File2应具有相同的行数和相同的起始字(s) 。即。当我运行File1和BadFile来测试BadFile是否遵循File1的格式时,我的程序会生成一个通行证。

我不需要存储关键字后面的东西(例如“hello”,“test”,在这种情况下为“测试”),但我应该能够区分有2行以“password”开头的行为我检查。

也有行没有“< ...>”。基本上,无论File1中的哪一个文件都必须在FileN中找到才能通过。

任何想法我应该用什么数据结构来实现它?我正在考虑数组散列,但对于我和这种情况来说似乎太复杂了。

回答

1
my $template_qfn = ...; 
my $file_qfn  = ...; 

my $template = do { 
    open(my $fh, '<', $template_qfn) or die $!; 
    local $/; 
    <$fh> 
}; 

my $template_pat = quotemeta($template); 
$template_pat =~ s/\\<[^<>\n]*\\>/[^\n]+/g; 
my $template_re = qr/^$template_pat\z/; 

my $file = do { 
    open(my $fh, '<', $file_qfn) or die $!; 
    local $/; 
    <$fh> 
}; 

die("File \"$file_qfn\" doesn't match template \"$template_qfn\"\n") 
    if $file !~ $template_re; 
+0

什么样病例的“Hello World”里我没有“<...>” ? – Sakura 2012-02-29 07:46:55

+0

这是检查,就像你问。 – ikegami 2012-02-29 07:51:34

+0

经过测试。修复了一个错误。 – ikegami 2012-02-29 07:55:39

0

这是一段代码,(通过打开的文件替代DATA)可以帮助你:

use strict; 
my @tokens = qw/username password password/; 
my $current = 0; 
my $line_number = 1; 

while(my $line = <DATA>) { 
    my $expected = $tokens[$current]; 
    if($line !~ m!^$expected !) { 
     die "Invalid format: expected '$expected' at data file line number: $line_number; line: $line" 
    } 
    $current = ++$current % scalar(@tokens); 
    $line_number++; 
} 

die "Invalid format; sequence incomplete" if $current != 0; 
print "Ok!\n"; 

__DATA__ 
username hello 
password test 
password testing 
+0

像“hello world”这样我没有“<...>”这种情况呢? – Sakura 2012-02-29 07:50:00

相关问题