【问题标题】:Issue while reading a property file in Perl在 Perl 中读取属性文件时出现问题
【发布时间】:2014-04-17 19:57:51
【问题描述】:

我想用 perl 读取一个属性文件。 我的属性文件 abc.properties 的格式为:

jdk=Path1:Path2:PathN
soa=Path1:Path2:PathN

这是我的代码:

#!/usr/bin/perl

my %o;
open my $in, "abc.properties" or die $!;
while(<$in>) {
   $o{$1}=$2 while m/(\S+)=(\S+)/g;
}
close $in;

for (keys %o) {
     my @value_array = @{$o{$_}};
     print "Key is $_ and value is @values\n";
}

输出是: 键是 jdk,值是 键是 soa,值是

我无法读取键对应的值。我的目标是读取值然后将其拆分:

作为 perl 新手,任何帮助将不胜感激!

【问题讨论】:

  • 每个键是否只有一个值?另外,use strict; use warnings; 也不见了。
  • 是的,每个键只有一个值包含多个冒号:
  • 总是use strict。总是use warnings

标签: perl


【解决方案1】:

如果您希望每个键只存储一个值,则无需创建值数组。

for (keys %o) {
     print "Key is $_ and value is $o{$_}\n";
}

此外,在与正则表达式匹配的行上,应使用if 而不是while。一行怎么能匹配多次?

添加use strict; use warnings; 会告知您所犯的一些错误(即混淆了@value_array 和@values)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-29
    • 2012-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-27
    • 1970-01-01
    相关资源
    最近更新 更多