2013-10-04 51 views
-1

這將是我的第一個問題。我想通過使用Perl來實現以下目標。
代碼應該搜索File2中File1中提到的參數,並將文件2中「:」的值替換爲File1中的值。代碼應該就地替換,並且不要更改/排序文件中參數的順序。Perl注意到一個文件中的變量,在另一個文件中搜索並替換它

文件1:

config1: abc 
config2: bcd 
config3: efg 

文件2:

config1: cba 
config2: sdf 
config3: eer 
config4: 343 
config5: sds 
config6: dfd 

輸出 - >文件2應該是這樣的:

config1: abc 
config2: bcd 
config3: efg 
config4: 343 
config5: sds 
config6: dfd 
+4

這聽起來像功課(更換就地並保持參數順序是在小KVP配置文件中具有零實際壽命相關性的任意約束)。你能告訴我你嘗試過什麼,遇到了什麼困難? StackOverflow不是「爲我做的工作/家庭作業」網站。 – DVK

回答

1
  • 使用File::Slurp讀取文件1
    • 對於每一行,使用split或正則表達式將鍵和值分開,並將此鍵值對添加到%file散列中。
  • 要真正地在原地替換,請使用-pi參數到Perl的命令行; (你可以嘗試使用Tie::Hash,但可能會更困難)。
  • 您可以通過閱讀文件2使用File::Slurp到一個哈希%文件2,在鋪設使用過的%hash2鍵循環%hash2值之上%file1值mimique這一點,使用後再次File::Slurp寫造成%hash2迴文件2在正確的循環中構造鍵 - valye字符串。

如果你有一個具體的步驟困難,請出示你做了什麼,什麼問題,所以我們可以幫助解決

+0

感謝您的迴應......我已經創建了一個使用正則表達式的工作代碼行......循環等......不是作業:P ......只是本網站的新用戶。 –

-1
use strict; 
use warnings; 

#store params from file1 
my (%params); 

open(my $FILE1, "< file1.txt") or die $!; 
my @arr = <$FILE1>; 
foreach(@arr){ 
    #extract key-value pairs \s* = any number of spaces, .* = anything 
    #\w+ = any sequence of letters (at least one) 
    my ($key, $value) = ($_ =~ /(\w+)\s*:\s*(.*)/); 
    $params{$key}=$value; 
} 
close $FILE1; 

open(my $FILE2, "< file2.txt") or die $!; 
my @arr2 = <$FILE2>; 
foreach(@arr2){ 
    my ($key, $value) = ($_ =~ /(\w+)\s*:\s*(.*)/); 
    #if the found key did exist in params, then replace the found value, with 
    #the value from file 1 (this may be dangerous if value contains regexp chars, 
    #consider using e.g. \Q...\E 
    if (exists $params{$key}) { 
     #replace the row in @arr2 inline using direct ref $_ 
     $_ =~ s/$value/$params{$key}/; 
    } 
} 
close $FILE2 
#replace/output the result /here to a different file, not to destroy 
open(my $FILE2W, "> file2_adjusted.txt") or die $!; 
print $FILE2W @arr2; 
close $FILE2W 
相關問題