2012-10-22 153 views
0

我有一个文件a.txt,并且我有文件b.txt.I正在读取这两个文件。如何在perl中追加文件

让我们假设A.TXT有:

Apple is a fruit. 
I like java. 
I am an human being. 
I am saying hello world. 

比方说b.txt有

I am the planet earth 

现在我试图寻找在A.TXT如特定的字符串:我是人。如果我找到这一行。我想在b.txt到a.txt.My输出文件的内容追加看起来应该有些这样的事

Apple is a fruit. 
I like java. 
I am the planet earth---->appended 
I am an human being. 
I am saying hello world. 

我尝试以下,但它不是帮助

open (FILE1 , "a.txt") 
my (@fpointer1) = <FILE>; 
close FILE1 

open (FILE2 , "b.txt") 
my (@fpointer1) = <FILE>; 
close FILE2 

#Open the a.txt again, but this time in write mode 
open (FILE3 , ">a.txt") 
my (@fpointer1) = <FILE>; 
close FILE3 

foreach $line (@fpointer1) { 

if (line to be searched is found) 
--> Paste(Insert) the contents of file "b.txt" read through fpointer2 

} 
+0

这是无效的Perl。大多数表达式之后你缺少';'。总是用'严格使用'和'使用警告'来启动你的文件。你也应该使用“open”和“lexical”文件句柄的三参数版本。 – dgw

回答

1

这里有一个快速和肮脏的工作例如:

use warnings; 
use 5.010; 

open FILE, "a.txt" or die "Couldn't open file: $!"; 
while (<FILE>){ 
$string_A .= $_; 
} 

open FILE, "b.txt" or die "Couldn't open file: $!"; 
while (<FILE>){ 
$string_B .= $_; 
} 
close FILE; 

$searchString = "I am an human being."; 


$resultPosition = index($string_A, $searchString); 

if($resultPosition!= -1){ 

$endPosition = length($string_A)+length($string_B)-length($searchString); 

$temp_String = substr($string_A, 0, $resultPosition).$string_B." "; 


$final_String =$temp_String.substr($string_A, $resultPosition, $endPosition) ; 
} 
else {print "String not found!";} 

print $final_String; 

有可能是这样做的更有效的方法。但你可以有一个想法。

0

这里为例

use strict; 

open(A, ">>a.txt") or die "a.txt not open"; 
open(B, "b.txt") or die "b.txt not open"; 

my @text = <B>; 
foreach my $l (@text){ 
     if ($l =~ /I am the planet earth/sg){ 
       print A $&; 
     } 
} 

我认为,像这样......