我的要求是读取一个文件并在每行的末尾添加一个值。谁能告诉我怎么做到这一点?
这是我的代码:
open( OFILE, "<$source_path" ) or die "could not open file";
while ( <OFILE> ) {
my @iline = ( $_ );
#print "@iline\n";
#print "$iline[0]\n";
#print "$iline[1]\n";
#push @iline, '4';
#print "@iline \n";
open( IFILE, ">$target_directory_pacss" );
{
foreach ( @iline ) {
#print IFILE "$_[0]".","."$_[1]".","."$_[2]" ;
#print "$_[0]".","."$_[1]".","."$ival" ;
#print "\n";
print IFILE "$_";
print "\n";
}
}
close( IFILE );
}
我到底想要的是
patie,1234
patie,1235
patie,1236
patie,1234,4
patie,1235,4
patie,1236,4
答案 0 :(得分:1)
下面提到的代码是实现所需输出的最简单方法。 我假设您只需要在每行的末尾添加一些东西,因为它保存了一个新文件。因此,根据您要求的输出,我附加了&#34;,4&#34;在每一行之后。
此代码逐行读取源文件,并使用所需的修改值写入新文件。
my $source_path = "file.txt";
my $target_directory_pacss = "file2.txt";
open(OFILE, "<$source_path") or die "could not open file";
open(IFILE, ">$target_directory_pacss");
while(<OFILE>) {
chomp;
print IFILE $_.",4\n";
}
close( OFILE);
close( IFILE );
使用 chomp :因为您需要在每行末尾删除换行符,然后再添加任何值。
输出:
patie,1234,4
patie,1235,4
patie,1236,4
答案 1 :(得分:-1)
您可以按照以下代码进行操作。您可以先在数组中读取整个文件,然后使用附加行将其记录到另一个文件中。
my $source_path = "source.txt";
my $target_directory_pacss = "destination.txt";
open(OFILE,"<$source_path") or die "could not open file";
chomp(my @lines = <OFILE>);
close(OFILE);
open(IFILE,">$target_directory_pacss");
foreach my $line(@lines){
print IFILE "$line"."EOL"."\n";
}
close(OFILE);
close (IFILE);
我添加了字符串&#34; EOL&#34;在上面代码的每一行的末尾。