如何使用Perl计算文本文件中的段落?

rob*_*jez 0 perl file paragraphs

我需要创建Perl代码,允许计算文本文件中的段落.我试过这个并不起作用:

open(READFILE, "<$filename")
or die "could not open file \"$filename\":$!";

$paragraphs = 0;

my($c);

while($c = getc(READFILE))
{
if($C ne"\n")
{
$paragraphs++;
}
}

close(READFILE);

print("Paragraphs: $paragraphs\n");
Run Code Online (Sandbox Code Playgroud)

Eug*_*ash 6

请参阅perlfaq5:如何按段落读取文件?

local $/ = '';  # enable paragraph mode
open my $fh, '<', $file or die "can't open $file: $!";
1 while <$fh>;
my $count = $.;
Run Code Online (Sandbox Code Playgroud)

  • local $/=''; (在一个小脚本中不会有所作为,但在一个更大的脚本中你可能会破坏另一个模块使用$ /) (2认同)