Perl 读取和写入同一文件
我使用在线找到的代码读取Perl脚本中的属性文件:Perl 读取和写入同一文件,perl,Perl,我使用在线找到的代码读取Perl脚本中的属性文件: open (CONFIG, "myfile.properties"); while (CONFIG){ chomp; #no new line s/#.*//; #no comments s/^\s+//; #no leading white space s/\s+$//; #no trailing white space next unless length; my ($var, $value) = s
open (CONFIG, "myfile.properties");
while (CONFIG){
chomp; #no new line
s/#.*//; #no comments
s/^\s+//; #no leading white space
s/\s+$//; #no trailing white space
next unless length;
my ($var, $value) = split (/\s* = \s*/, $_, 2);
$$var = $value;
}
也可以在while循环中写入文本文件吗?假设文本文件如下所示:
#Some comments
a_variale = 5
a_path = /home/user/path
write_to_this_variable = ""
my $filename = 'myfile.properites';
open(my $in, '<', $filename) or die "Unable to open '$filename' for read: $!";
my $newfile = "$filename.new";
open(my $out, '>', $newfile) or die "Unable to open '$newfile' for write: $!";
while (<$in>) {
s/(write_to_this_variable =) ""/$1 "some text"/;
print $out;
}
close $in;
close $out;
rename $newfile,$filename or die "unable to rename '$newfile' to '$filename': $!";
如何将一些文本放入
写入此变量中?覆盖具有可变长度记录(行)的文本文件并不实际。复制文件是正常的,如下所示:
#Some comments
a_variale = 5
a_path = /home/user/path
write_to_this_variable = ""
my $filename = 'myfile.properites';
open(my $in, '<', $filename) or die "Unable to open '$filename' for read: $!";
my $newfile = "$filename.new";
open(my $out, '>', $newfile) or die "Unable to open '$newfile' for write: $!";
while (<$in>) {
s/(write_to_this_variable =) ""/$1 "some text"/;
print $out;
}
close $in;
close $out;
rename $newfile,$filename or die "unable to rename '$newfile' to '$filename': $!";
my$filename='myfile.properites';
打开(我的$in,,$newfile)或死亡“无法打开$newfile进行写入:$!”;
而(){
s/(将此变量=)写入“/$1”一些文本“/;
打印美元;
}
以美元收盘;
收尾美元;
重命名$newfile、$filename或“无法将“$newfile”重命名为“$filename”:$!”;
如果文本包含非字母数字,您可能必须使用类似\Q
的内容来清理文本。这是一个程序示例,该程序使用模块来读取和写入像您这样的简单配置文件。据我所知,它是唯一一个将保留原始文件中任何注释的模块
有两点需要注意:
$props{''}{write_to_this_variable}
中的第一个散列键构成将包含该值的配置文件部分的名称。如果文件中没有节,则必须在此处使用空字符串
如果需要在a值周围加引号,那么在分配给哈希元素时必须显式地添加引号,就像我在这里使用的““Some text”
我认为程序的其余部分是不言自明的
use strict;
use warnings;
use Config::Std { def_sep => ' = ' };
my %props;
read_config 'myfile.properties', %props;
$props{''}{write_to_this_variable} = '"Some text"';
write_config %props;
输出
#Some comments
a_variale = 5
a_path = /home/user/path
write_to_this_variable = "Some text"
尝试模式参数-。为什么不尝试使用一个模块来为您进行读写。例如,请参阅或。您应该使用三参数版本的open
,同时使用词法文件句柄和错误检查。例如,打开我的$config\u fh,'