【问题标题】:Perl reading configuration file without using ModulesPerl读取配置文件而不使用模块
【发布时间】:2011-07-02 11:49:54
【问题描述】:

假设我有一个配置文件。

配置.csv

Server,Properties
"so-al-1","48989"
"so-al-3","43278"
"so-al-5","12345"

我需要使用 perl 脚本从文件中检索服务器和属性,以便在我的脚本中使用变量的值。此外,我们的客户端服务器不希望我们安装任何模块。

那么如何在不使用模块的情况下以变量形式阅读此文档?

open(FILE,"Config.csv");
undef($/); #sucks the entire file in at once
while(<FILE>){
    (@words)=split(/\s+/);  
}
close FILE;

for (@words){
    s/[\,|\.|\!|\?|\:|\;]//g; #removed punctuation
    $word{$_}++;
}

for (sort keys %word){
    print "$_ occurred $word{$_} times\n";
}

我确实尝试了上述方法,但它没有将它放入我想要的哈希中。

已编辑:我复制代码太快,错过了一行。

已编辑:我刚刚发现 StackOverflow 中已经存在这样的问题。 How can I parse quoted CSV in Perl with a regex?

【问题讨论】:

  • 您似乎找到了可以执行您想要的操作的 sn-ps,但它们并没有正确地一起使用。请问:你为什么不想使用模块?如果没有易于使用的 Text::CSV,解析 csv 会很困难且容易出错。最后,您要达到的目标是什么?获取键值配置对(如您的问题所示)或按照您的代码建议查找文件中唯一单词的实例数?
  • 代码中的主要错误表明您不精通 Perl,这很好。但是,您甚至没有阅读您提到的同一个 .csv 文件。你怎么能指望这段代码能工作?
  • 抱歉,当我在做其他事情时,我复制代码的速度有点太快了。我只想在另一个 perl 脚本中使用该变量。将此 csv 解析为哈希就可以了。

标签: perl file variables configuration


【解决方案1】:

遵循“您应该使用 CSV 模块”的通常警告,此方法有效:

#!/usr/bin/env perl
use warnings;
use strict;

my $header_str=<DATA>;
chomp $header_str;
my @header=$header_str =~ /(?:^|,)("(?:[^"]+|"")*"|[^,]*)/g;
my %fields;
my @temp;
my $line;

while($line=<DATA>){
    chomp $line;
    @temp = $line =~ /(?:^|,)("(?:[^"]+|"")*"|[^,]*)/g;
    for (@temp) {
        if (s/^"//) { 
            s/"$//; s/""/"/g;
        }
     }

     $fields{$temp[0]}=$temp[1];
}

print "$_\t\t" for (@header);
print "\n";
print map { "$_\t\t$fields{$_}\n" } sort keys %fields;

__DATA__
Server,Properties
"so-al-1","48989"
"so-al-3","43278"
"so-al-5","12345"

输出:

Server      Properties      
so-al-1     48989
so-al-3     43278
so-al-5     12345

【讨论】:

  • 当您发现自己在输入诸如“/(?:^|,)("(?:[^"]+|"")*"|[^,]*)/" 之类的内容时`,是时候重新考虑使用模块了。
  • @socket puppet: >>I 会使用一个模块,但 OP 声明 no modules!
  • 哇.. 这很复杂。我想这就是模块如此重要的原因。谢谢。天才编码。
【解决方案2】:
#!/usr/bin/perl
use warnings;
use strict;

while (<DATA>) {
    chomp;
    next unless my($key,$value) = split /,/;
    s/^"//, s/"$// for $key, $value;
    print "key=$key value=$value\n";
}

__DATA__
Server,Properties
"so-al-1","48989"
"so-al-3","43278"
"so-al-5","12345"

【讨论】:

  • 这将在受保护的引用字段内以逗号分隔。即,"don't, split", inside quotes 将是 3 个字段。再说一遍——为什么你应该使用 CSV 模块...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-02
  • 2011-05-25
  • 1970-01-01
  • 2020-10-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多