如何将选中信息及前置内容存入数组?Perl脚本问题求助
问题描述
我有一个需要读取的文件。file1.txt 的内容如下:
information1 information2 information3 information4 information5 information6 information7
执行终端命令:
perl scripts.pl --select information3
期望返回选中的information3及其之前的内容:
information3 information2 information1
执行命令:
perl scripts.pl --select information6
期望结果:
information6 information5 information4 information3 information2 information1
当前代码
use Getopt::Long qw(GetOptions);; use Switch; my $read_file = 'file1.txt'; my $info_name; my @name; my $select; GetOptions( "select|t=s"=> \$select, ); open(READ_FILE,"<", $read_file) || die "Cannot open file $read_file to Read! - $!"; while (<READ_FILE>) { my $info_name = $_; if ($info_name =~ m/$select/) { $info_name = $_; push (@name,($info_name)); } } close(READ_FILE); print "@name ";
现有问题
执行命令:
perl scripts.pl --select information3
仅得到结果:
information3
无法获取目标行之前的所有内容。
解决方案
当前代码仅收集匹配到的目标行,未处理之前的内容。可以先读取文件所有行到数组,定位目标行位置后,截取目标行到开头的片段并反转输出:
use Getopt::Long qw(GetOptions); my $read_file = 'file1.txt'; my $select; GetOptions( "select|t=s" => \$select ) or die "Invalid options\n"; # 读取所有行到数组,保留换行符 open my $fh, '<', $read_file or die "Cannot open $read_file: $!"; my @lines = <$fh>; close $fh; # 找到目标行的索引 my $target_idx; for my $i (0..$#lines) { # 使用\Q\E避免正则元字符干扰,精确匹配整行 if ($lines[$i] =~ /^\Q$select\E$/) { $target_idx = $i; last; } } if (defined $target_idx) { # 截取目标行到开头的片段,反转后输出 my @result = reverse @lines[0..$target_idx]; print @result; } else { print "No matching line found for '$select'\n"; }
说明
- 先将文件所有行读入数组
@lines,方便后续定位目标行位置 - 遍历数组时用精确匹配规则,避免部分匹配(比如不会把
information30识别为information3) - 截取目标行到开头的内容并反转,正好符合目标行在前、之前的行倒序排列的需求
- 增加了未找到目标行的提示,提升脚本健壮性
- 移除了无用的
Switch模块,简化代码结构
内容的提问来源于stack exchange,提问作者DM 256
相关产品推荐
相关产品推荐

