如何使用perl在文件的开头添加信息

时间:2011-10-10 12:38:57

标签: perl

我有c文件,我需要在c文件的乞讨时添加一些信息。我有一个哈希表,其中键作为数字,值作为字符串。通过使用该表我正在搜索字符串找到我正在向c文件添加信息。我是通过使用我在“add information to a file using perl”问题中发布的脚本来做到这一点的。现在我需要在c文件的beginging中添加信息,如果我找到了string.In我的脚本我在字符串之前添加。 我现在应该怎么做。  提前谢谢。

2 个答案:

答案 0 :(得分:2)

答案 1 :(得分:0)

(从我刚刚在the SitePoint forums给出的答案中交叉发布到似乎是同一个问题的答案。)

可悲的是,没有办法在文件开头插入信息而不必重写整个文件,所以你需要读入整个文件(而不是一次只读一行),确定哪个字符串(s)出现在内容中,将相应的信息项写入新文件,并(最后!)将原始内容写入新文件:

#!/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';
相关问题