问题描述
|
例如,我有一个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