2013-10-21 31 views
1

我有一个Perl脚本,它将包含多个句子(Sentences.txt)的文本文件作为输入。每个句子用白线分隔。该脚本为Sentences.txt中的每个句子创建单独的文本文件。例如,Sent1.txt为第一句Sentences.txtSent2.txt为第二句Sentences.txt等。在perl中使用printf函数打印%字符

问题是当我尝试使用printf功能从Sentences.txt打印一个句子到相应的单独的文件(SentX.txt)和句子包含%字符。我该如何解决这个问题?

这是代码:

#!/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"; 
+4

你确定你需要在这里使用'printf'吗?也许使用'print'? – Suic

回答

5

如果你只想把句子,你发现了它,为什么不使用print?这与%没有问题。

如果需要printf您需要使用

$sentence =~ s/%/%%/g; 
2

fprintf代表“格式”,而不是“文件”与%%替换每个%,例如。您缺少格式参数。

printf $fesal "%s", $mom_line; 

但是,你可以简单地使用

print $fesal $mom_line; 

要包括%(s)printf格式,加倍:%%

相关问题