You need to enable JavaScript to run this app. Perl读取文件匹配指定序列统计three出现次数的代码修正
优惠活动
大模型
产品
解决方案
定价
更多

Perl读取文件匹配指定序列统计three出现次数的代码修正

原代码核心问题
  • 计数逻辑漏算连续three:嵌套循环碰到第一个three时仅执行1次$count++,立刻跳出找three的循环进入查找four的分支,后续连续出现的three因为处于找four的循环范围内,不会触发计数逻辑,直接被跳过,碰到连续三个three的场景只能统计到1次,和预期值偏差很大。
  • 字符串比较存在隐患:读取文件行后没有用chomp去掉末尾换行符,实际比较的字符串自带换行,正常场景下无法匹配到目标文本,仅在特殊测试条件下能触发逻辑。
  • 循环跳转逻辑失效:多层嵌套的last语句仅能跳出最内层循环,遇到序列中断时无法完整回退到初始匹配状态,容易出现计数错乱。
修正方案

采用线性状态机替代多层嵌套循环,逐行读取文件时按匹配进度切换状态,完整覆盖序列匹配与计数需求:

  • 按序列顺序逐段匹配one→two→four→five
  • 在two与four的区间内,每遇到一个three就累加计数
  • 任意阶段出现序列中断时,立刻重置计数与匹配状态
修正后代码
use warnings;
use strict;

my $temp1 = "test.txt"; # 替换为实际读取的文件路径
open(my $fh, "<", $temp1) or die "Could not open file $temp1: $!";

my $three_total = 0;
my $current_state = 0;
# 状态定义:
# 0=等待序列起始one
# 1=等待two
# 2=统计two到four之间的three
# 3=等待序列结尾five

while (my $line = <$fh>) {
    chomp $line;
    if ($current_state == 0) {
        $current_state = 1 if $line eq "one";
    } elsif ($current_state == 1) {
        $current_state = 2 if $line eq "two";
    } elsif ($current_state == 2) {
        if ($line eq "three") {
            $three_total++;
        } elsif ($line eq "four") {
            $current_state = 3;
        } else {
            # 序列中断,重置所有状态
            $current_state = 0;
            $three_total = 0;
        }
    } elsif ($current_state == 3) {
        if ($line eq "five") {
            # 检测到完整匹配序列,保留当前three计数
            print "检测到完整的目标序列\n";
        } else {
            # 序列中断,重置
            $current_state = 0;
            $three_total = 0;
        }
    }
}
close $fh;
print "目标序列中three的总出现次数:$three_total\n";
测试效果

针对提供的测试文件,代码会识别到完整的one→two→three→three→three→four→five序列,统计得到的three总数为3,符合预期。

内容的提问来源于stack exchange,提问作者Alexx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.20 21:54:10