繁体   English   中英

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

[英]How to read multi-line values from a file using Perl

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

##
## Start of property1
##
##
Property1=\
a:b,\
a1:b1,\
a2,b2
##
## Start of propert2
##
Property2=\
c:d,\
c1:d1,\
c2,d2

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

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

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

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

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

提前致谢

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

while (<>) {
  $_ .= <> while s/\\\n// and not eof;
}

下面的程序做我认为你想要的。 我在read循环中放置了一个print调用,以显示已经在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

产量

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"]],
}

更新

我再次阅读了您的问题,我认为您可能更喜欢不同的数据表示形式。 此变体将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;

产量

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 },
}

假设您的文件不是太大,这是一个简单的方法:

use strict;
use warnings;

open FILE, "my_file.txt" or die "Can't open file!";

{
    local $/;
    my $file = <FILE>;
    #If \ is found at the end of the line, delete the following line break.
    $file =~ s/\\\n//gs;
}

每当一行以\\结尾时,将删除以下换行符。 这会将每个多行属性放在一行上。

缺点是这会将整个文件读入内存; 如果您的输入文件非常大,您可以将其调整为逐行遍历文件的算法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM