Perl脚本开发求助:实现命令行水果信息的文件追加与更新
Perl脚本:命令行输入添加/追加水果信息到文本文件
需求
- 若命令行指定的水果不存在于目标文本文件中,则添加该水果名称及对应信息(例如示例中的jackfruit)。
- 若命令行指定的水果已存在于文件中,则将对应信息追加到该水果条目下的最顶部(如info1对应apple,直接放在apple行的下一行)。
示例命令
<script> -fruit apple,orange,jackfruit -info <info1>,<info2>,<info3>
输入文件示例
apple x y orange a b
期望输出
apple <info1> x y orange <info2> a b jackfruit <info3>
现有代码
use strict; use warnings; use Getopt::Long; use Tie::File; my $fruit; my $info; if (! GetOptions( "fruit=s" => \$fruit, "info=s" => \$info, )){ print "\nEntered Arguments are not enough!\nPlease Use Switch '-help' or '-h' For More Information.\n"; exit; } my $split_info; my $split_fruit; my @split_info = split(',', $info); my @split_fruit = split(',', $fruit); tie my @file, 'Tie::File', 'filenamee.txt' or die $!; for (0 .. $#file) { if ($file[$_] eq "$split_fruit[0]") { splice @file, $_ + 1, 0, "\t$split_info[0]\n"; } }
代码问题与改进方案
现有代码仅处理了第一个水果和对应信息,未覆盖所有输入的水果-信息对,也未处理水果不存在的情况,同时Tie::File的行元素默认不带换行符,添加\n会导致多余空行。以下是修改后的完整代码:
use strict; use warnings; use Getopt::Long; use Tie::File; my ($fruit_str, $info_str); # 解析命令行参数,添加-help选项 GetOptions( "fruit=s" => \$fruit_str, "info=s" => \$info_str, "help|h" => sub { print "Usage: $0 -fruit <fruit1,fruit2,...> -info <info1,info2,...>\n"; exit 0; } ) or do { print "参数错误!使用 -help 查看用法\n"; exit 1; }; # 验证参数是否完整 unless ($fruit_str && $info_str) { print "缺少必要参数!使用 -help 查看用法\n"; exit 1; } # 拆分水果和信息数组 my @fruits = split(',', $fruit_str); my @infos = split(',', $info_str); # 确保水果和信息数量匹配 if (@fruits != @infos) { print "水果数量与信息数量不匹配!\n"; exit 1; } # 绑定文件到数组,自动处理换行 tie my @file, 'Tie::File', 'filenamee.txt' or die "无法打开文件: $!"; # 遍历每个水果-信息对 for my $i (0 .. $#fruits) { my $target_fruit = $fruits[$i]; my $target_info = "\t" . $infos[$i]; # 缩进用制表符 my $found = 0; # 检查文件中是否存在该水果 for my $line_idx (0 .. $#file) { # 去除行首尾空白后匹配(避免文件中行有多余空格) if (trim($file[$line_idx]) eq $target_fruit) { # 在水果行的下一行插入新信息 splice @file, $line_idx + 1, 0, $target_info; $found = 1; last; } } # 如果未找到该水果,追加到文件末尾 unless ($found) { push @file, $target_fruit; push @file, $target_info; } } # 解除文件绑定 untie @file; # 辅助函数:去除字符串首尾空白 sub trim { my $str = shift; $str =~ s/^\s+|\s+$//g; return $str; }
改进点说明
- 参数校验:添加了
-help选项,验证参数完整性,检查水果与信息数量是否匹配。 - 遍历所有水果:循环处理每个输入的水果-信息对,不再仅处理第一个。
- 处理水果不存在的情况:遍历文件未找到目标水果时,自动在文件末尾添加水果名和对应信息。
- 行匹配优化:使用
trim函数去除行首尾空白,避免文件中行存在多余空格导致匹配失败。 - Tie::File换行处理:不再手动添加
\n,Tie::File会自动处理文件的换行符,避免多余空行。
内容的提问来源于stack exchange,提问作者Blurman
相关产品推荐
相关产品推荐

