使用Perl中的OPEN CLOSE函数在文件开头添加一个字符串

时间:2014-10-29 16:48:54

标签: perl

我的代码对我的任何修改都不起作用。除了附加在开放闭合函数中没有任何作用。

#!/usr/local/bin/perl 
my $file = 'test'; 
open(INFO, $file); 
print INFO "Add this line please\n"; 
print INFO "First line\n"; 
close(INFO);

2 个答案:

答案 0 :(得分:3)

你需要告诉perl你想要什么类型的文件句柄

open(INFO, ">", "$file")|| die "Cannot open $file";

这将创建并写入文件。

抬头看 http://perldoc.perl.org/functions/open.html

答案 1 :(得分:2)

默认open(INFO, $file) will take the file handle in read mode('<')。因此,除非您指定write mode('>'),否则无法将值打印到文件中。当你编写代码时,你应该使用:use strict;并使用警告;这将有所帮助。

<强>代码:

use strict;
use warnings;
my $InputFile = $ARGV[0];
open(FH,'<',"$InputFile")or die "Couldn't open the file $InputFile: $!";
my @file_content = <FH>; 
close(FH);
open(FH,'>',"$InputFile") or die "Cannot open $InputFile: $!";
#String to be added at the begining of the file
my $file = "test";  
print FH $file . "\n";
print FH @file_content;
close(FH);
相关问题