【问题标题】:I can I separate multiple logical pages in a text file I create in Perl?我可以在我用 Perl 创建的文本文件中分隔多个逻辑页面吗?
【发布时间】:2010-03-16 22:44:18
【问题描述】:

到目前为止,我已经成功地通过打开一个文件作为外部循环的一部分进行输出并在写入所有输出后关闭它来为单个文件生成输出。我使用了一个计数变量 ($x) 并将 .txt 附加到它上面以创建一个文件名,并将它写入与我的 perl 脚本相同的目录中。我想将代码升级一点,提示用户输入文件名,打开该文件一次且仅一次,然后每页写一个“打印的字母”。这可能在纯文本中吗?据我了解, chr(12) 是一个 ascii 换行符,可以让我接近我想要的,但有更好的方法吗?提前谢谢各位。 :)

sub PersonalizeLetters{
    print "\n\n Beginning finalization of letters...";
    print "\n\n I need a filename to save these letters to.";
    print "\n Filename > ";
    $OutFileName = <stdin>;
    chomp ($OutFileName);
    open(OutFile, ">$OutFileName");                 
    for ($x=0; $x<$NumRecords; $x++){
        $xIndex = (6 * $x);
        $clTitle = @ClientAoA[$xIndex];
        $clName = @ClientAoA[$xIndex+1];        
        #I use this 6x multiplier because my records have 6 elements.
        #For this routine I'm only interested in name and title.
        #Reset OutLetter array
        #Midletter has other merged fields that aren't specific to who's receiving the letter.      
        @OutLetter = @MiddleLetter;
        for ($y=0; $y<=$ifLength; $y++){
            #Step through line by line and insert the name.
        $WorkLine = @OutLetter[$y];                 
        $WorkLine =~ s/\[ClientTitle\]/$clTitle/;
        $WorkLine =~ s/\[ClientName\]/$clName/;
        @OutLetter[$y] = $WorkLine;

        }           

        print OutFile "@OutLetter";
        #Will chr(12) work here, or is there something better?
        print OutFile chr(12);
        $StatusX = $x+1;
        print "Writing output $StatusX of $NumRecords... \n\n";
    }
    close(OutFile);
}

【问题讨论】:

  • ASCII 12 是换页(您所描述的是:声明页面的结尾),而不是换行。
  • 据我所知,您认为 chr(12) 是在纯文本文件中实现分页的方法是正确的。您用来处理数据的方法(担心 6 倍索引乘数等)似乎非常尴尬。更好的做法是将您的数据存储为散列列表,每个散列包含信件收件人所需的所有信息。要了解如何使用此类更丰富的数据结构,请参阅 perldoc.perl.org/perlreftut.htmlperldoc.perl.org/perldsc.html

标签: perl text


【解决方案1】:

将“页面”与表单提要分开,但您必须在每页之后进行,而不是在结尾处。我不确定PersonalizeLetters 应该做什么,但看起来你用它来打印所有字母。在这种情况下,我认为您只需要对其进行一些重组。在子例程之外进行所有设置,传入文件名,然后为每条记录执行您需要执行的操作。处理记录后,打印换页:

sub PersonalizeLetters
    {
    my( $OutFileName ) = @_;

    open my $out, '>', $OutFileName 
        or die "Could not open $OutFileName: $!";                 

    for( $x=0; $x < $NumRecords; $x++ )
        {
        print "Writing output $x of $NumRecords...\n\n";
        print $out $stuff_for_this_record;
        print $out "\f";
        }           

    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多