2012-02-29 53 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

相關問題