これは、正規表現で後方参照を使用して非常に簡単に行われます
以下のプログラムは、何らかの空白と同じ文字列が出現する{RP}
か、その後に続くものを再度検索します。{/RP}
コマンドラインパラメータとしてデータファイルが必要です
use strict;
use warnings;
my $count;
while (<>) {
$count++ if m|(\{/?RP\})\s+\1|;
}
print "$count occurrences";
出力
3 occurrences
アップデート
問題の説明は非常に不明確ですが、私はそれを再解釈するために最善を尽くしました. {/RP} <some whitespace> {/RP}
このコードは、 を含む行の直後に を含む行が続くすべてのケースを探します{RP} <some whitespace> {RP}
。空白の入力行はすべて無視されます
use strict;
use warnings;
my @pair;
my $count;
while (<>) {
next unless /\S/;
push @pair, $_;
next unless @pair >= 2;
shift @pair while @pair > 2;
if ($pair[0] =~ m|\{/RP\}\s+\{/RP\}| and $pair[1] =~ m|\{RP\}\s+\{RP\}|) {
$count++;
@pair = ();
}
}
print "$count occurrences\n";
出力
1 occurrences
アップデート
OK、もう一度試してみましょう。このプログラムは、すべての行の 3 番目と 4 番目の空白で区切られた列をチェックします。it のペアが{RP}
に設定$depth
される1
たびに、{/RP}
$depth がゼロに設定され、それが以前にゼロで$count
ない場合は増分されます$depth
単一の{RP}
orのみを含むすべての行{/RP}
は単に無視されることに注意してください。あなたの説明からは、この状況でどのようなアクションが必要かを判断することは不可能です
use strict;
use warnings;
my $depth;
my $count = 0;
while (<>) {
my @fields = map $_ // '', (split)[4,5];
if (grep($_ eq '{RP}', @fields) == 2) {
$depth = 1;
}
elsif (grep($_ eq '{/RP}', @fields) == 2) {
$count++ if $depth;
$depth = 0;
}
}
print "$count occurrences\n";
出力
1 occurrences