You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Perl配置文件写入异常:使用>模式却出现追加堆叠问题

问题分析与解决方案

你的代码出现配置内容重复堆叠的核心原因是**@file_aggiornato数组未使用my声明为局部变量**,导致它成为全局变量。每次调用cambiaNThreads函数时,新读取的配置行都会追加到这个全局数组中,而非重新创建空数组。最终写入文件时,数组累积了多轮读取的内容,造成配置重复叠加。

修复后的代码

只需在cambiaNThreads函数内用my声明@file_aggiornato,让它成为函数的局部变量即可解决问题:

#!/usr/bin/perl
use strict;
use warnings; # 建议开启,提前捕获变量未声明等潜在问题

my $conf_file = "Configuration.txt";
my $times_file = "tempi.txt";

sub cambiaNThreads {
    my $numero = shift;
    my @file_aggiornato; # 声明为局部变量,每次调用函数时重新初始化

    open my $in, '<', $conf_file or die "Impossibile leggere il file $conf_file: $!";

    while( <$in> )
    {
        if ($_ =~ /number_node_/) 
        {
            $_ =~ s/:\s*\K\d+/$numero/;
        }

        push @file_aggiornato, $_;
    }

    close($in) or die "Impossibile chiudere il file '$conf_file': $!";

    open my $out, '>', $conf_file or die "Impossibile scrivere sul file $conf_file: $!";

    foreach (@file_aggiornato) {
        print $out $_;
    }

    close($out) or die "Impossibile chiudere il file '$conf_file': $!";   
}

open my $out, '>>', $times_file or die "Impossibile scrivere sul file $times_file: $!";

for (1..4) {
    my $n_th = $_ ** 2;
    cambiaNThreads($n_th);

    print $out "\n =============$n_th=============";
    print $out qx(make pthreads_cond_o3_noout);
}

close($out) or die "Impossibile chiudere il file '$times_file': $!";

额外建议

  • 始终在Perl脚本开头添加use strict;和use warnings;,这会强制变量声明并发出潜在问题警告,避免类似全局变量误用的低级错误。
  • 所有变量尽量用my声明为局部变量(除非确实需要全局作用域),保持代码的封装性和可维护性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 04:32:42