如何逐行读取和更新 pm 文件? [英] How to read and update a pm file line by line?

查看:38
本文介绍了如何逐行读取和更新 pm 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Perl 脚本中,我们从 pm 文件中检索配置详细信息.用户使用脚本的界面更改配置详细信息后,应将相同的值写回到 pm 文件中.

In a Perl script, we are retrieving configuration details from a pm file. After the user changes the configuration details using the script's interface, the same values should be written back in the pm file.

例如,我有以下 config.pm 文件:

For example, I have the following config.pm file:

$SourcePrimUserHost = '10.226.33.233';
$SourcePrimUserPort = '33002';
$SourceGroupsHost = '10.226.33.233';
$SourceGroupsPort = '33002';

我正在从 Perl 脚本中读取这些值.我想将更新的值存储回 config.pm 文件.

I'm reading these values from a Perl script. I want to store updated values back to config.pm file.

我们怎样才能做到这一点?期待您的帮助.

How can we do this? Looking forward to your help.

推荐答案

不是一个好的设计选择.

  1. Perl 模块可以(应该!)以用户可以读取但不能写入的方式安装.
  2. 如果该模块被多个用户或多个 Perl 程序使用,则 conf 将是系统全局的,而不是特定于应用程序的.
  3. 如果程序的多个实例同时运行,就会出现问题.

我建议使用像 YAML 这样的数据序列化格式,尽管 JSON、Freeze/Thaw 和 Dumper 可能是其他参赛者.此配置最好存储在单独的文件中.

I would recommend using a data serialization format like YAML, although JSON, Freeze/Thaw and Dumper may be other contestants. This configuration would best be stored in a seperate file.

如果您必须将数据存储在同一个文件中,则可以使用 __DATA__ 标记.后面的所有内容都可以作为 DATA 文件句柄在代码内部访问,并且不会被 perl 执行.在更新配置时找到这个令牌也很简单.如果模块被称为 Foo::Bar:

If you have to store the data in the same file, you could use the __DATA__ token. Everything behind that is accessible inside the code as the DATA filehandle, and will not be executed by perl. It is also trivial to find this token when updating the configuration. If the module is called Foo::Bar:

my $serialized_stuff = ...;
my $self_loc = $INC{"Foo/Bar.pm"}; # %INC holds the location for every loaded module.
my $tempfile = ...;
open $SELF, "<", $self_loc or die ...;
open $TEMP, ">", $tempfile or die ...;
# don't touch anything before __DATA__
while(<$SELF>) {
  print $TEMP $_;
  last if /^__DATA__$/;
}
print $TEMP $serialized_stuff;
close $TEMP; close $SELF;
rename $tempfile => $self_loc or die ...;

这篇关于如何逐行读取和更新 pm 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆