Har*_*itz 1 printing perl printf
我有一个Perl脚本,它将包含几个句子(Sentences.txt)的文本文件作为输入.每个句子用白线分隔.该脚本为每个句子创建单独的文本文件Sentences.txt.例如,Sent1.txt对于第一句话Sentences.txt,Sent2.txt对于第二句Sentences.txt等等.
当我尝试使用函数将句子打印Sentences.txt到相应的单独文件(SentX.txt)printf并且句子包含一个%字符时,问题就来了.我怎么解决这个问题?
这是代码:
#!/usr/bin/perl -w
use strict;
use warnings;
# Separate sentences
my $sep_dir = "./sep_dir";
# Sentences.txt
my $sent = "Sentences.txt";
open my $fsent, "<", $sent or die "can not open '$sent'\n";
# read sentences
my $kont = 1;
my $previous2_line = "";
my $previous_line = "";
my $mom_line = "";
while(my $line = <$fsent>){
chomp($line);
#
$previous2_line = $previous_line;
#
$previous_line = $mom_line;
#
$mom_line = $line;
if($mom_line !~ m/^\s*$/){
# create separate sentence file
my $fitx_esal = "Sent.$kont.txt";
open my $fesal, ">", $fitx_esal or die "can not open '$fitx_esal'\n";
printf $fesal $mom_line;
close $fesal or die "can not close '$fitx_esal'.\n";
$kont++;
}
}
close $fsent or die "can not close '$sent'.\n";
Run Code Online (Sandbox Code Playgroud)
如果你只是想把你发现的句子,为什么不使用print?这与%没有问题.
如果printf需要,您将需要用%%替换每个%,例如使用
$sentence =~ s/%/%%/g;
Run Code Online (Sandbox Code Playgroud)