如何解决如何指示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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。