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 个元素,每个元素都是一个元素数组(包含“重要”一词的行)

非常感谢任何帮助 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 - 如何将变量数组存储在另一个数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5578771/

相关文章:

perl - 如何在Perl中将文件与目录区分开?

perl - 使用 perl 连接苹果 APNS 的问题

perl - 我应该如何改进我的 perl 应用程序部署过程?

Python 与 perl 排序性能

xml - 查找两个元素之间的相对 XPath 的最有效方法是什么?

perl - 如何在 Perl 中将日期转换为纪元时间?

perl - 路径::Class::Unicode and error handling

regex - Perl 脚本与单行脚本 - 正则表达式的功能差异

regex - Perl 的 unpack ("A4/A*") 正则表达式形式的长度+字节语法

Perl bool 值、否定(以及如何解释)?