Perl을 사용하여 텍스트 파일의 단락을 어떻게 계산할 수 있습니까?
-
19-09-2019 - |
문제
텍스트 파일에서 단락을 계산할 수있는 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");
해결책
이중 뉴 라인 ( " n n")으로 단락을 결정하고 있다면 다음을 수행합니다.
open READFILE, "<$filename"
or die "cannot open file `$filename' for reading: $!";
my @paragraphs;
{local $/; @paragraphs = split "\n\n", <READFILE>} # slurp-split
my $num_paragraphs = scalar @paragraphs;
__END__
그렇지 않으면 코드에서 " n n"을 변경하여 자신의 단락 분리기를 사용하십시오. 패턴을 사용하는 것이 좋습니다. \n{2,}
, 누군가가 Enter 키에 미치게 된 경우를 대비하여.
메모리 소비가 걱정된다면 이와 같은 일을하고 싶을 수도 있습니다 (읽기 어려운 코드는 죄송합니다) :
my $num_paragraphs;
{local $/; $num_paragraphs = @{[ <READFILE> =~ /\n\n/g ]} + 1}
자신의 코드를 계속 사용하려면 변경할 수 있습니다. if($C ne"\n")
에게 if($c eq "\n")
.
다른 팁
보다 perlfaq5 : 단락으로 파일에서 어떻게 읽을 수 있습니까?
local $/ = ''; # enable paragraph mode
open my $fh, '<', $file or die "can't open $file: $!";
1 while <$fh>;
my $count = $.;
초기 Perl 책을 살펴보십시오 http://www.perl.org/books/beginning-perl/. 특히 다음 장이 도움이됩니다. http://docs.google.com/viewer?url=http%3A%2F%2fblob.perl.org%2FBooks%2FBeginning-perl%2F3145_chap06.pdf
제휴하지 않습니다 StackOverflow