2011-10-10 84 views
0

我有c文件,我需要在c文件的乞求中添加一些信息。我有一個散列表,其中鍵爲數字和值作爲字符串。通過使用該表,我正在搜索如果字符串發現我將信息添加到C文件。我通過使用腳本發佈了「add information to a file using perl」問題。現在我需要在c文件的beginging處添加信息,如果我發現字符串。在我的腳本中,我在字符串之前添加。 我現在該做什麼。 在此先感謝。如何在文件的開頭添加信息使用perl

回答

0

(從我剛纔介紹了the SitePoint forums到這似乎是同一個問題的答案交叉發佈。)

可悲的是,沒有辦法插入在文件的開頭信息,而無需重寫整個的東西,所以你需要讀入整個文件(而不是一次一行),確定哪些字符串出現在內容中,將相應的信息項寫入新文件,以及(最後!)將原始內容寫入新文件:

#!/usr/bin/env perl 

use strict; 
use warnings; 

use File::Slurp; 

my %strings = (
    'string1' => "information \n", 
    'string2' => "information2 \n", 
    'string3' => "information3 \n", 
); 
my $test_string = "(" . join("|", keys %strings) . ")"; 

# First make a list of all matched strings (including the number of times 
# each was found, although I assume that's not actually relevant) 

my $code = read_file('c.c'); 
my %found; 
while ($code =~ /$test_string/g) { 
    $found{$1}++; 
} 

# If %found is empty, we didn't find anything to insert, so no need to rewrite 
# the file 

exit unless %found; 

# Write the prefix data to the new file followed by the original contents 

open my $out, '>', 'c.c.new'; 
for my $string (sort keys %found) { 
    print $out $strings{$string}; 
} 

print $out $code; 

# Replace the old file with the new one 
rename 'c.c.new', 'c.c'; 
+0

你好,我想你的代碼,但also.if你看我的代碼什麼,我發表在「用perl信息添加到文件」 question.I有兩個哈希表它不給任何錯誤和輸出我用這兩個,我發現在c文件中的蜇和我添加信息在c文件中的字符串之前。但在你的代碼我dint發現你在哪裏添加信息到C文件。提出這樣的問題。@ Dave – viswa

+0

@viswa :新的信息通過'for my $ string(sort keys%found)'循環寫入文件。由於SitePoint上的問題指定將信息添加到現有文件的開頭,因此此代碼只是修改了磁盤上的文件,並未向終端提供任何輸出。如果您希望更改後的版本顯示在屏幕上,請從兩個'print $ out ...'語句中刪除'$ out'。 –

+0

非常感謝你的幫助,現在我嘗試了,它的工作很好。 – viswa