简体   繁体   English

在Perl中,如何处理配置文件中的续行?

[英]In Perl, how can I handle continuation lines in a configuration file?

So I'm trying to read in a config. 因此,我正在尝试读取配置。 file in Perl. Perl中的文件。 The config file uses a trailing backslash to indicate a line continuation. 配置文件使用尾部反斜杠表示行继续。 For instance, the file might look like this: 例如,文件可能如下所示:

  === somefile ===
  foo=bar
  x=this\
  is\
  a\
  multiline statement.

I have code that reads in the file, and then processes the trailing backslash(es) to concatenate the lines. 我有读取文件中的代码,然后处理结尾的反斜杠以连接行的代码。 However, it looks like Perl already did it for me. 但是,看起来Perl已经为我做了。 For instance, the code: 例如,代码:

  open(fh, 'somefile');
  @data = <fh>;
  print join('', @data);

prints: 印刷品:

  foo=bar
  x=thisisamultiline statement

Lo and behold, the '@data = ;' 看吧,“ @ data =;” statement appears to have already handled the trailing backslash! 语句似乎已经处理了结尾的反斜杠!

Is this defined behavior in Perl? 这是Perl中定义的行为吗?

I have no idea what you are seeing, but that is not valid Perl code and that is not a behavior in Perl. 我不知道您看到了什么,但这不是有效的Perl代码,并且不是Perl中的行为。 Here is some Perl code that does what you want: 这是一些Perl代码,可以满足您的需求:

#!/usr/bin/perl

use strict;
use warnings;

while (my $line = <DATA>) {
    #collapse lines that end with \
    while ($line =~ s/\\\n//) {
        $line .= <DATA>;
    }
    print $line;
}

__DATA__
foo=bar
x=this\
is\
a\
multiline statement.

Note: If you are typing the file in on the commandline like this: 注意:如果要在命令行中像这样输入文件:

perl -ple 1 <<!
foo\
bar
baz
!

Then you are seeing the effect of your shell, not Perl. 然后,您将看到外壳的效果,而不是Perl。 Consider the following counterexample: 考虑以下反例:

printf 'foo\\\nbar\nbaz\n' | perl -ple 1

My ConfigReader::Simple module supports continuation lines in config files, and should handle your config if it's the format in your question. 我的ConfigReader :: Simple模块支持配置文件中的连续行,并且如果您的配置是问题的格式,则应处理您的配置。

If you want to see how to do it yourself, check out the source for that module. 如果您想看看自己如何做,请查看该模块的源代码。 It's not a lot of code. 它不是很多代码。

I don't know what exactly you are doing, but the code you gave us doesn't even run: 我不知道您到底在做什么,但是您提供给我们的代码甚至无法运行:

=> cat z.pl
#!/usr/bin/perl
fh = open('somefile', 'r');
@data = <fh>;
print join('', @data);

=> perl z.pl
Can't modify constant item in scalar assignment at z.pl line 2, near ");"
Execution of z.pl aborted due to compilation errors.

And if I change the snippet to be actual perl: 如果我将代码段更改为实际的perl:

=> cat z.pl
#!/usr/bin/perl
open my $fh, '<', 'somefile';
my @data = <$fh>;
print join('', @data);

it clearly doesn't mangle the data: 它显然不会破坏数据:

=> perl z.pl
foo=bar
x=this\
is\
a\
multiline statement.

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

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