2013-01-07 213 views
0

我使用这个代码我在网上找到读取性能在我的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) = split (/\s* = \s*/, $_, 2); 
    $$var = $value; 
} 

是否posssible也写这个while循环中的文本文件?比方说,该文本文件看起来像这样:

#Some comments 
a_variale = 5 
a_path = /home/user/path 

write_to_this_variable = "" 

我怎么可以把一些文字write_to_this_variable

+1

尝试MODE参数 - http://perldoc.perl.org/functions/open.html。 –

+4

你为什么不尝试使用模块为你做阅读和写作?例如。请参阅[Config :: Tiny](https://metacpan.org/module/Config::Tiny)或[Config :: Simple](https://metacpan.org/module/Config::Simple)。 – stevenl

+3

你应该使用'open'三个参数版本以及词法文件句柄和错误检查。例如'打开我的$ config_fh,'<','myfile.properties'或者死掉$ !;' – dgw

回答

1

覆盖具有可变长度记录(行)的文本文件并不实际。这是正常的文件,复制的东西是这样的:

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': $!"; 

您可能需要sanitse你喜欢的东西\Q写,如果它包含非字母数字文本。

0

这是一个程序的例子,它使用Config::Std模块读取一个像你的简单配置文件写入。据我所知,它是唯一的模块,将保留在原始文件中的任何评论。

有两点需要注意:

  1. $props{''}{write_to_this_variable}形式的配置文件部分将包含值的名称的第一个哈希键。如果没有分区,那么你必须在这里使用一个空字符串

  2. 如果你需要引用一个值,那么当你指定散列元素时,你必须显式地添加这些元素,就像我一样这里用'"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"