如何使用Perl从文件中读取多行值

Thr*_*ati 3 perl

我有一个属性文件,比方说

##
## Start of property1
##
##
Property1=\
a:b,\
a1:b1,\
a2,b2
##
## Start of propert2
##
Property2=\
c:d,\
c1:d1,\
c2,d2
Run Code Online (Sandbox Code Playgroud)

请注意,任何给定属性的值可以分为多行.

我想用Perl读取这个属性文件.这在Java中运行良好,因为Java使用反斜杠支持多行值,但在Perl中它是一个噩梦.

在上面的属性文件中有两个属性 - Property1Property2- 每个属性与一个字符串相关联,我可以根据分隔符,:

对于给定的属性(比如说Property1)和给定的列(比如说a1)我需要返回第二列(这里b1)

代码应该能够忽略注释,空格等.

提前致谢

Bor*_*din 5

在Perl中,大多数文本处理(包括处理反斜杠延续行)都非常简单.你只需要一个像这样的读取循环.

while (<>) {
  $_ .= <> while s/\\\n// and not eof;
}
Run Code Online (Sandbox Code Playgroud)

下面的程序做我认为你想要的.我print在read循环中调用了一个调用来显示已经在continuation行上聚合的完整记录.我还演示了提取b1您给出的字段作为示例,并显示了输出,Data::Dump以便您可以看到创建的数据结构.

use strict;
use warnings;

my %data;

while (<DATA>) {
  next if /^#/;
  $_ .= <DATA> while s/\\\n// and not eof;
  print;
  chomp;
  my ($key, $values) = split /=/;
  my @values = map [ split /:/ ], split /,/, $values;
  $data{$key} = \@values;
}

print $data{Property1}[1][1], "\n\n";

use Data::Dump;
dd \%data;


__DATA__
##
## Start of property1
##
##
Property1=\
a:b,\
a1:b1,\
a2,b2
##
## Start of propert2
##
Property2=\
c:d,\
c1:d1,\
c2,d2
Run Code Online (Sandbox Code Playgroud)

产量

Property1=a:b,a1:b1,a2,b2
Property2=c:d,c1:d1,c2,d2
b1

{
  Property1 => [["a", "b"], ["a1", "b1"], ["a2"], ["b2"]],
  Property2 => [["c", "d"], ["c1", "d1"], ["c2"], ["d2"]],
}
Run Code Online (Sandbox Code Playgroud)

更新

我再次阅读了您的问题,我认为您可能更喜欢不同的数据表示形式.此变体将proerty值保留为哈希值而不是数组数组,否则其行为是相同的

use strict;
use warnings;

my %data;

while (<DATA>) {
  next if /^#/;
  $_ .= <DATA> while s/\\\n// and not eof;
  print;
  chomp;
  my ($key, $values) = split /=/;
  my %values = map { my @kv = split /:/; @kv[0,1] } split /,/, $values;
  $data{$key} = \%values;
}

print $data{Property1}{a1}, "\n\n";

use Data::Dump;
dd \%data;
Run Code Online (Sandbox Code Playgroud)

产量

Property1=a:b,a1:b1,a2,b2
Property2=c:d,c1:d1,c2,d2
b1

{
  Property1 => { a => "b", a1 => "b1", a2 => undef, b2 => undef },
  Property2 => { c => "d", c1 => "d1", c2 => undef, d2 => undef },
}
Run Code Online (Sandbox Code Playgroud)