使用Perl,如何从具有两个可能的记录分隔符的文件中读取记录?

Jam*_*mes 1 string perl file-read

这是我想要做的:

我想将一个文本文件读入一个字符串数组.我希望在文件中的某个人物(主要是读取字符串终止;|).

例如,以下文字

Would you; please
hand me| my coat?

将被收起来像这样:

$string[0] = 'Would you;';
$string[1] = ' please hand me|';
$string[2] = ' my coat?';
Run Code Online (Sandbox Code Playgroud)

我能在这样的事情上得到一些帮助吗?

小智 6

这样做.在保留你正在拆分的令牌时使用split的技巧是使用零宽度回溯匹配:split(/(?<=[;|])/, ...).

注意:mctylr的答案(当前评分最高)实际上并不正确 - 它会在换行符上拆分字段,b/c它一次只能在文件的一行上运行.

gbacon使用输入记录分隔符($/)的答案非常聪明 - 它既节省空间又节省时间 - 但我认为我不想在生产代码中看到它.将一个拆分令牌放在记录分隔符中,而另一个拆分令牌让我觉得有点太不明显了(你必须用Perl来对抗它),这将使其难以维护.我也不确定为什么他会删除多个换行符(我认为你没有要求?)以及为什么他只是在'|'终止记录结束时才这样做.

# open file for reading, die with error message if it fails
open(my $fh, '<', 'data.txt') || die $!; 

# set file reading to slurp (whole file) mode (note that this affects all 
# file reads in this block)
local $/ = undef; 

my $string = <$fh>; 

# convert all newlines into spaces, not specified but as per example output
$string =~ s/\n/ /g; 

# split string on ; or |, using a zero-width lookback match (?<=) to preserve char
my (@strings) = split(/(?<=[;|])/, $string); 
Run Code Online (Sandbox Code Playgroud)