Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store variable-arrays inside another array?

Tags:

perl

I have a perl-query on saving arrays inside another array. A related query was asked before(How do I add an array ref to the middle of an existing array in Perl?), but I could not find answer to mine, so I am posting it here.

I have 10 text files, each having approximately 100 lines of text. I want to pick all those lines containing the word "important". Script for doing this operation is below. I save all lines containing word "important" in an array. So, from each text file, I get an array. I want to save all those arrays inside another array ?

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);   
}

elements of @sub_array changes every time, so, how do I preserve elements of all sub_arrays ? I would like to have final output as @main_array, which contains 3 elements, each element is an array of elements (lines containing the word "important")

Any help is much appreciated TIA

like image 925
chakri Avatar asked Mar 23 '26 07:03

chakri


1 Answers

I would do it slightly differently to bvr. But his points still stand.

# 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;
}
like image 174
Dave Cross Avatar answered Mar 24 '26 23:03

Dave Cross



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!