例如,我有一个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 = "nn"; # 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
输出:
命令1命令2执行myscript opt1=val1opt2=val2