in reply to Re^5: How to create an output file for each input file
in thread How to create an output file for each input file

Thanks for the document. When I run my code (with variables defined) I am able to open a new file, but instead of it closing and then a second file being created, the dumby data is appended to the original single file. Is that because I'm using

open(OUTPUT_FILE, ">>$verifile")||die "Can't open file: $!";

close OUTPUT_FILE;
  • Comment on Re^6: How to create an output file for each input file

Replies are listed 'Best First'.
Re^7: How to create an output file for each input file
by apl (Monsignor) on Apr 03, 2008 at 01:04 UTC
    '>>' says "append to an existing file". I believe a single '>' says 'create if necessary, over-write if it already exists'.

    When you do the print, do you print OUTPUT_FILE?

    If you post your current code, I (or someone else; it's bedtime for me) could better comment.

      I'm slowly piecing it together. Thanks so much for your insight, I'll share more later, getting late here too.
        Okay, I figured it out. In my original code snippet, I was creating (what I thought) was a unique file name using the date. But because I was only going down to the second, and the script was running so quickly on test data, it thought it should "append" to the existing file. I redid the naming convention for the outbox file to add the original name of the input file, thereby creating a unique output file after each pass of the foreach loop. The final test code below:

        ########Test Variables
        $outbox = "G:\\outbox\\";
        $inbox = "G:\\inbox\\";
        $archive = "G:\\archive\\";
        $log = "G:\\samslog.txt";


        ####################get the names of all .dat files in inbox directory
        opendir(DIR,$inbox);
        @files = grep(/\.TAB$/,readdir(DIR));
        closedir(DIR);


        ################
        ## loop through the TAB files###
        foreach $file (@files) {
        ##Open the .TAB file for reading
        open(TAB_FILE, $inbox.$file) || die "Can't open file: $!";

        #create file name
        $verifile = $outbox.$file."_FIXED.TAB";

        #print column headings in output file
        open(OUTPUT_FILE, ">>$verifile")||die "Can't open file: $!";
        print OUTPUT_FILE "Column1 Column2 Column3\n";


        ##Loop through each line of the file (1 part number per line)
        while (<TAB_FILE>){
        ##Use chomp to get rid of carriage returns and spaces
        chomp;
        ($column1, $column2, $column3) = split("\t");
        print OUTPUT_FILE $column1."\t".$column2."\t".$column3."\n";


        close TAB_FILE;
        close OUTPUT_FILE;


        }# end for each file