perl – 如何在另一个数组中存储变量数组?

前端之家收集整理的这篇文章主要介绍了perl – 如何在另一个数组中存储变量数组?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个关于在另一个数组中保存数组的perl查询.在( How do I add an array ref to the middle of an existing array in Perl?)之前询问了一个相关的查询,但我找不到我的答案,所以我在这里发帖.

我有10个文本文件,每个文件大约有100行文本.我想选择包含“重要”一词的所有行.执行此操作的脚本如下.我在数组中保存包含单词“important”的所有行.所以,从每个文本文件中,我得到一个数组.我想将所有这些数组保存在另一个数组中?

my @list_of_files = ("input1.txt","input2.txt","input3.txt"); my $list_of_files = @list_of_files;

for ($file=0,$file<$list_of_files; $files++){
 open INPUT_FILE,"$list_of_files[$file]" or die "can't open $file : $!";
 my @input = <INPUT_FILE>;
 my $size = @input;

 for ($num=0; $num<$size; $num++){
  if ($input[$num] =~ m/important/) {
   push (@sub_array,$output);
  }
 }
 close INPUT_FILE;
 push (@main_array,\@sub_array);   
}

@sub_array的元素每次都会更改,因此,如何保留所有sub_arrays的元素?我希望最终输出为@main_array,其中包含3个元素,每个元素都是一个元素数组(包含单词“important”的行)

任何帮助都非常感谢TIA

解决方法

我会对bvr略有不同.但他的观点仍然有效.

# use qw() to define line with less punctuation
my @list_of_files = qw(input1.txt input2.txt input3.txt);

my @lines_in_file;

foreach my $file (@list_of_files) {
  open(my $in,'<',$file) or die "can't open $file : $!";

  # declare an array,not a scalar
  my @lines;

  # idiomatic use of while(<>) puts each record into $_
  while (<$in>) {
    # /../ works on $_ by default.
    # Postfix condition is more readable
    push @lines,$_ if /important/;
  }

  # Take reference to array and push it onto main array
  push @lines_in_file,\@lines;
}

猜你在找的Perl相关文章