2014-01-25 47 views
0

讀取像下面這樣的配置文件我可以通過使用數組(通過使用拆分和連接函數)存儲「info」的值並能夠檢查總值每一個數組的值,但我在閱讀每個信息值下的文件。從perl中的配置文件中讀取文件的值和路徑

[abc] 
Info=alerts,requestes 
[alerts] 
total=23 
/home/value/date/readme.txt 
/root/File1 
/home/File2 
/users/cord/File3 
[requestes] 
Total=87 
C:\user\user1\file1 
C:\user\user1\file2 
C:\user\user1\file3 

你對此有什麼想法嗎?我們如何通過使用perl來實現這一點。 我的期望輸出像警報 /home/value/date/readme.txt /根/文件1 /家庭/文件2 /用戶/線/文件3 requestes的文件 的C本 FILES:\用戶\ USER1 \文件1 C:\ user \ user1 \ file2 C:\ user \ user1 \ file3

+0

您的預期產出是多少? – fugu

+0

輸出應該像提醒 這 FILES /home/value/date/readme.txt /根/文件1 /家庭/文件2 /用戶/線/文件3 requestes 的C 文件:\用戶\ USER1 \ file1 C:\ user \ user1 \ file2 C:\ user \ user1 \ file3 – Scg

+1

您是否嘗試過http://search.cpan.org/~gcarls/Config-IniFiles/IniFiles.pm? – Toto

回答

-1

我不認爲你需要CPAN模塊來做​​到這一點,但它可能會有所幫助。我寫了一些代碼,希望能讓你開始做這件事。

有很多方法可以做到這一點,但一種方法是隻讀取文件,並在使用正則表達式確定哪行中包含哪些數據或內容時將其解析爲散列。

#!/bin/perl 
use strict; 
use warnings; 


my $file = <<'EOD'; 
[abc] 
Info=alerts,requests 
[alerts] 
total=23 
/home/value/date/readme.txt 
/root/File1 
/home/File2 
/users/cord/File3 
[requests] 
Total=87 
C:\user\user1\file1 
C:\user\user1\file2 
C:\user\user1\file3 
EOD 

my %info_hash; 

my @file_contents = split('\n', $file); 


my $title = shift @file_contents; 
$title =~ s/\[(.*)\]/$1/g; 

print "Title: $title\n"; 
my $info_string = shift @file_contents; 
$info_string =~ s/^.*?=//; 
my @info = split(',', $info_string); 

my $key; 

for my $line (@file_contents) { 

    chomp $line; 
    if ($line =~ /^\[(.*?)\]/) { 
     $key = $1; 
    } elsif ($line =~ /^total=(.*)/i){ 
     $info_hash{$key}{total} = $1; 
    } else { 
     push @{$info_hash{$key}{values}}, $line; 
    } 
} 

for my $entry (keys %info_hash) { 
    print "Total for $entry is " . $info_hash{$entry}{total} . "\n"; 
    print join(" ", @{$info_hash{$entry}{values}}) . "\n"; 
} 

該程序將其解析爲哈希散列。結構看起來像這樣:

%info_hash = 
'alerts' => 
{ 
     'values' => [ 
        '/home/value/date/readme.txt', 
        '/root/File1', 
        '/home/File2', 
        '/users/cord/File3' 
        ], 
     'total' => '23' 
}; 
'requests' => 
{ 
     'values' => [ 
        'C:\\user\\user1\\file1', 
        'C:\\user\\user1\\file2', 
        'C:\\user\\user1\\file3' 
        ], 
     'total' => '87' 
}; 

讓我知道如果您有任何關於代碼如何工作的問題。這可能不是你想要的,但它是一個起點,並舉例說明如何存儲數據。

+0

謝謝,在這裏我無法獲得文件的數量,即價值觀的價值如何可以得到.. – Scg

+0

對於總數使用'$ info_hash {$ entry} {total}'和一個存儲所有文件名的數組使用'@ {$ info_hash {$ entry} {values}}'。查看他們打印的最後一個循環,瞭解如何獲取它們的示例。希望這可以幫助! – chilemagic

+0

這段代碼很複雜,足以保證在CPAN上查看更多可支持的版本 – justintime

相關問題