如何在 Perl 中处理配置文件?

发布于 2024-09-25 16:58:46 字数 190 浏览 1 评论 0原文

我正在重构一个旧脚本,该脚本在不同站点上执行一些操作。它需要使用一个配置文件,该文件现在是一个手动解析的文本文件,具有以下格式:

label:domain:username:password:path

当然,行数可能是无限的。

我知道有一些处理配置文件的模块。哪一个最适合这种情况?

I'm refactoring an old script that does some operations on different sites. It needs to use a configuration file which is now a manually parsed text file with this format:

label:domain:username:password:path

Of course the number of lines is potentially unlimited.

I know there are a few modules which deal with config files. Which one is the best for this situation?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

孤君无依 2024-10-02 16:58:47

如果您想更改格式,请查看此处的建议:

如何在 Perl 中管理配置文件?

如果您希望解析现有格式,该格式看起来更像是逗号分隔的文件比“配置”文件,所以我会说使用 Text::CSV (它允许您在构造函数中选择分隔符,因此您可以使用冒号分隔而不是逗号分隔),或者对于非常大的文件文本::CSV_XS。

use Text::CSV; # Example adapted from POD

my @rows;
my $csv = Text::CSV->new ( { sep_char => ":" } )  
             or die "Cannot use CSV: ".Text::CSV->error_diag ();

open my $fh, "<:encoding(utf8)", "test.conf" or die "test.conf: $!";
while ( my $row = $csv->getline( $fh ) ) {
    push @rows, $row; # $row is arrayref containing your fields
}
$csv->eof or $csv->error_diag();
close $fh;

If you are looking to change the format, please look at the recommendations here:

How do you manage configuration files in Perl?

If you're looking to parse the existing format, that format looks to be more of a comma-separated file than a "configuration" file, so I'd say go with Text::CSV (it allows you to choose a separator character in a constructor, so you can do colon-separated instead of comma-separated), or for very large files Text::CSV_XS.

use Text::CSV; # Example adapted from POD

my @rows;
my $csv = Text::CSV->new ( { sep_char => ":" } )  
             or die "Cannot use CSV: ".Text::CSV->error_diag ();

open my $fh, "<:encoding(utf8)", "test.conf" or die "test.conf: $!";
while ( my $row = $csv->getline( $fh ) ) {
    push @rows, $row; # $row is arrayref containing your fields
}
$csv->eof or $csv->error_diag();
close $fh;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文