如何指示Perl将在特定字符上折断的多行视为单行?

问题描述

| 例如,我有一个txt文件,其中在&符上打断了多行电话。
command1

command2

execute myscript &
        opt1=val1 &
        opt2=val2

...
在打开文件时,是否有办法告诉Perl将这三行当作单行考虑而忽略
&
?     

解决方法

打开文件时不行。但是在阅读时加入他们并不难:
open(my $in,\'<\',\'file.txt\') or die;
while (<$in>) {
  $_ .= <$in> while s/&\\s*\\z//;

  # $_ now contains a complete record
  ...
}
    ,如果记录之间总是有多个换行符,请考虑使用“记录分隔符”来读取它们。然后,您可以对&使用快速检查,并执行拆分/合并:
use English \'-no_match_vars\'; 

sub read_records {
    local $RS = \"\\n\\n\";  # or,for the machoistic,$/ works too without English
    ... # open the file
    while (my $record = <$fh>) {
        chomp $record;               # uses $RS for what to remove,nice!
        if ($record =~ /&\\s*$/ms) {  # & at the end of *any* line (w/only spaces)
            $record = join \' \',split /\\s*&\\s+/,$record; # pull them out
        }
        ... # do something with the record
    }
}
    ,我假设您的输入大小合适,因此请将整个内容读入标量,将其清理干净,然后处理更友好的结果。
#! /usr/bin/env perl

use strict;
use warnings;

sub read_input {
  my($fh) = @_;
  local $/;
  scalar <$fh>;
}

my $commands = read_input \\*DATA;

$commands =~ s/&\\n//g;
print $commands;

__DATA__
command1

command2

execute myscript &
        opt1=val1 &
        opt2=val2
输出: command1 命令2 执行myscript opt1 = val1 opt2 = val2     

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...