user9437648
user9437648

Reputation: 3

Unable store all the outputs to array in Perl

I am reading the lines from a file and input it to commands.

open my $handle, '<', $path_to_file;
foreach  $line (<$handle>) {
  my @output  = `cmd`;

I want to store each output to array. But unable to store it , it overwrites the previous value

Upvotes: 0

Views: 78

Answers (1)

Dave Cross
Dave Cross

Reputation: 69314

open my $handle, '<', $path_to_file;
foreach  $line (<$handle>) {
  my @output  = `cmd`;
} # I added this closing brace.

You have a couple of problems here.

Firstly, each time around the loop, you are declaring a new, empty, instance of @output. So declare the variable outside of the loop.

my @output;
open my $handle, '<', $path_to_file;
foreach  $line (<$handle>) {
  @output  = `cmd`;
}

There's still a problem here though. You're overwriting the whole of @output in each iteration of your loop. You want to add your data to the end of @output. So instead of assigning a value to the array, you should push() a new element to the end of the array.

my @output;
open my $handle, '<', $path_to_file;
foreach  $line (<$handle>) {
  push @output, `cmd`;
} 

Update: As Borodin points out in a comment, push() imposes list context on the backticks, so they'll return a list where each element is a single line from the output of your command. You might want to tame that behaviour by either ensuring that each execution of the command returns a single string (perhaps with embedded newlines):

push @output, scalar `cmd`;

Or create a two-dimensional array where each element of @array is a reference to another array containing all of the lines of output from a single execution of the command:

push @output, [ `cmd` ];

Upvotes: 3

Related Questions