Perl字符串转数组及模板填充代码优化问题咨询
问题1:数据拆分与数组存储修正
你的拆分代码打印两个值是因为数据文件包含两行有效数据,循环遍历每行时会打印该行的第8个字段($slipt_string[7]),这是代码的正常行为。但当前代码存在数组存储无效的问题:@array定义在循环内部,每次循环都会重新初始化,导致无法保存所有行的数据。以下是修正后的代码:
#!/usr/bin/perl -w use strict; # 开启严格模式,避免变量未声明等潜在问题 my $file_input = "./log_ex_7/input_data.txt"; my @all_data; # 全局数组存储所有数据行 open (FILE_INPUT,"<$file_input") || die ("Can not open $file_input: $!"); foreach my $string (<FILE_INPUT>) { chomp($string); next if $string =~ /^#/; # 跳过表头行 my @split_fields = split(/\s+/, $string); push @all_data, \@split_fields; # 将每行字段作为数组引用存入,方便后续按行访问 # 若需打印每行的int_flag字段,保留以下语句;否则注释 print "$split_fields[7]\n"; } close FILE_INPUT; # 验证数组存储结果(可选) print "所有存储的数据:\n"; foreach my $row (@all_data) { print join(" ", @$row), "\n"; }
修正说明:
- 将
@array移到循环外部,改为存储每行字段的数组引用,避免每次循环重置数组 - 用
next if简化表头行判断逻辑,代码更简洁 - 错误提示加入
$!,打印系统级错误信息,便于调试
问题2:模板填充代码优化
原代码存在大量重复if判断、频繁IO操作、数组索引映射易出错等问题。优化方案采用哈希表映射字段名与值,一次性读取模板后批量替换占位符,减少IO开销,提升代码可读性与可维护性。
优化后的代码如下:
#!/usr/bin/perl -w use strict; use warnings; my $data_file = "./log_ex_7/input_data.txt"; my $output_file = "./output_data.txt"; my $template_file = "./log_ex_7/template.txt"; # 1. 读取数据文件,解析为哈希数组(每行对应一个哈希,键为字段名) my @data_rows; open my $fh_data, "<", $data_file or die "无法打开$data_file: $!"; while (my $line = <$fh_data>) { chomp $line; next if $line =~ /^#/; my @fields = split(/\s+/, $line); # 按表头定义字段与值的映射 my %row = ( addr_1 => $fields[0], data_1 => $fields[1], data_2 => $fields[2], exp_data_1 => $fields[3], exp_data_2 => $fields[4], type => $fields[5], check_type => $fields[6], int_flag => $fields[7], ); push @data_rows, \%row; } close $fh_data; # 2. 一次性读取模板内容到字符串 open my $fh_template, "<", $template_file or die "无法打开$template_file: $!"; local $/; # 取消行分隔符,读取整个文件 my $template_content = <$fh_template>; close $fh_template; # 3. 遍历数据行,替换模板并写入输出文件 open my $fh_output, ">", $output_file or die "无法打开$output_file: $!"; for my $idx (0..$#data_rows) { my $row = $data_rows[$idx]; my $stt = $idx + 1; # 生成stt编号 # 复制模板内容进行替换 my $content = $template_content; # 批量替换所有占位符 $content =~ s/<addr_1>/$row->{addr_1}/g; $content =~ s/<data_1>/$row->{data_1}/g; $content =~ s/<data_2>/$row->{data_2}/g; $content =~ s/<exp_data_1>/$row->{exp_data_1}/g; $content =~ s/<exp_data_2>/$row->{exp_data_2}/g; $content =~ s/<type>/$row->{type}/g; $content =~ s/<check_type>/$row->{check_type}/g; $content =~ s/<int_flag>/$row->{int_flag}/g; $content =~ s/<stt>/$stt/g; print $fh_output $content; } close $fh_output; # 打印输出结果(可选) system("cat $output_file");
优化说明:
- 使用哈希表存储每行数据,字段名直接映射值,避免数组索引的混乱与错误
- 一次性读取模板文件,减少IO操作次数,提升效率
- 批量替换占位符,替代原代码中大量重复的
if判断,代码更简洁易维护 - 使用词法文件句柄(
my $fh_data)替代旧式裸字文件句柄,安全性更高
内容的提问来源于stack exchange,提问作者Tố Ngồ
相关产品推荐
相关产品推荐

