Jaeyoung Park Jaeyoung Park - 8 days ago 5
Perl Question

Perl - a way to run a script multiple time and append output files

I would like to run a perl script multiple times and append output files in a file.

Let's say I have a perl script (sparc_sub.pl) that generate an output file, sparc_sub.output. I would like to run it multiple times. In every time run, it retunes the same output file (sparc_sub.output), but the content is different.

I know '>>' is the sign if I would like to append to the end of the file, so I used the sign to open the output files in a loop. However, the output file, sparc_sub.output always stores the result of the last run. (not appending)

Any help is appreciated.

sparc_top.pl

use strict;
use Math::BigInt;
use 5.010;
use List::Util qw(sum);

my $s;
my $done=3;
my $script="sparc_sub.pl";
my @output;
my $filename ='sparc_sub.output';

for ($s=0; $s < $done; $s++) {
system('perl',$script)==0 or die "failed to execute $script: \$?=$?";
open(my $fh, '>>', $filename) or die "Could not open file '$filename' $!";
close $fh;
}

Answer

You have opened the file and then immediately closed it without even writing anything to it.

open(my $fh, '>>', $filename) or die "Could not open file '$filename' $!";
print $fh "this data goes to file";
close $fh;

I have a perl script sparc_sub.pl that generate an output file, sparc_sub.output

So with each run the same file will be generated. I think you want to create a new file which will keep appending the data from sparc_sub.output. If that's the case then do below.

open(my $fh2, '>>', 'all_outputs') or die "Could not open file 'all_outputs' $!";

for ($s=0; $s < $done; $s++) {
    system('perl',$script)==0 or die "failed to execute $script: \$?=$?";
    #sparc_sub.output has been generated. 
    #Now take the data from this file and append it to a final file
    open(my $fh, '<', 'sparc_sub.output') or die "Could not open file '$filename' $!";
    my @data = <$fh>;
    print $fh2 @data;
}

Now all_outputs file contains the data from sparc_sub.output file which was generated multiple times in the loop.