【问题标题】:How to append file in perl如何在perl中附加文件
【发布时间】:2012-10-22 10:33:58
【问题描述】:

我有一个文件 a.txt 和一个文件 b.txt。我正在读取这两个文件。

假设 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。我的输出文件应该看起来有些像这样的

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

}

【问题讨论】:

  • 这不是有效的 perl。在大多数表达式之后,您都缺少;。始终以 use strict;use warnings; 开头文件。您还应该使用open 的三参数版本和词法文件句柄。

标签: perl


【解决方案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;

可能有更有效的方法来做到这一点。但你可以有一个想法。

【讨论】:

    【解决方案2】:

    这里是一个例子

    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 $&;
            }
    }
    

    我想,像这样……

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-27
      • 2011-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-27
      相关资源
      最近更新 更多