my $text ='<span>by <small itemprop="author">J.K. Rowling</small><span>by <small itemprop="author">J.K. Rowling</small><span>by <small itemprop="author">J.K. Rowling</small>'
if ($text =~ m/<span>by <small itemprop="author">(. ?)<\/small>/ig){
$author = $1;
$authorcount{$author} =1;
}
$authorcounttxt = "authorcount.txt";
open (OUTPUT3, ">$authorcounttxt");
foreach $author (sort { $authorcount{$b} <=> $authorcount{$a} } keys %authorcount){
print OUTPUT3 ("$author\t\t$authorcount{$author}\n");
}
close (OUTPUT3);
所需的輸出是:
J.K. Rowling 3
但是我只得到:
J.K. Rowling 1
uj5u.com熱心網友回復:
if ($text =~ m/.../ig){ $author = $1; $authorcount{$author} =1;
這是一個if陳述句,表示內部塊最多只能輸入一次,即是否存在第一個匹配項。您可能打算做一個while陳述句來輸入每個匹配的內部塊:
while ($text =~ m/.../ig){ $author = $1; $authorcount{$author} =1;
uj5u.com熱心網友回復:
將您的替換if為 awhile以遍歷您的正則運算式匹配的所有匹配項,而不僅僅是第一個匹配項:
while ($text =~ m/<span>by <small itemprop="author">(. ?)<\/small>/ig){
$author = $1;
$authorcount{$author} = 1;
}
另請注意:使用正則運算式決議 HTML 充滿危險。考慮使用可以正確決議 HTML 的模塊,例如Mojo::DOM 。
uj5u.com熱心網友回復:
正如之前的海報已經指出的那樣,問題隱藏在 中if ( $text =~ /.../gi ),它只評估true并阻止執行一次。
您正在尋找可以使用或回圈實作的陣列背景關系中的處理匹配。forwhile
以下代碼片段演示了解決方案的眾多方法之一。
use strict;
use warnings;
use feature 'say';
my(%authors, $fname, $text, $re);
$fname = 'authorcount.txt';
$text = '<span>by <small itemprop="author">J.K. Rowling</small><span>by <small itemprop="author">J.K. Rowling</small><span>by <small itemprop="author">J.K. Rowling</small>';
$re = qr/<span>by <small itemprop="author">(.*?)<\/small>/;
$authors{$1} for $text =~ /$re/gi;
open my $fh, ">", $fname
or die "Can't open $fname";
say $fh "$_ $authors{$_}" for sort keys %authors;
close $fh;
注意:此代碼適用于您的示例$text = '...',如果您打算處理復雜HTML檔案,那么Mojo::DOM是解決問題的正確工具。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/489478.html
