3

I am very new to Perl (just seen one Youtube video on it). I want to make a script that takes will take two .csv files and append them together and make a new .csv file. I don't want the two .csv files that are being appended to be altered. I also want to make this script take in a user input as the file to be merged (right now the two appended .csv files are in the same directory).

The error I keep getting is: print() on closed filehandle OUT at line 1 (#2) (W closed) The filehande you're printing on got itself closed sometime before now. Check your control flow

But I never used the close command so how are my filehandles closing?

use strict;
use warnings;
use diagnostics;
use feature 'say';
use feature "switch";
use v5.22;

# Ask for Base File
say "What is the base file you want to use?";
my $base_file = <STDIN>;
chomp $base_file;
open (BASE, '<', $base_file) or die "Couldn't find the base file you are entered: $base_file ";

# Ask for Append File
say "What is the file you want to append to the base file?";
my $append_file = <STDIN>;
chomp $append_file;
open (APPEND, '<', $append_file) or die "Couldn't find the append file you are entered: $append_file ";

# Create new File with new name
say "What is the name of the new file you want to create?";
my $new_file = <STDIN>;
open (OUT, '>>', $new_file);
chomp $new_file;
while(my $base_line = <BASE>) {
        chomp $base_line;
        print OUT $base_line;
}
tarkan
  • 69
  • 1
  • 8
  • Notes: (1) When you `use v5.22;` the features `say` and `switch` are enabled (so there is no need for `use feature ...`), and so is `strict`. (2) The [feature switch](https://perldoc.perl.org/feature.html#The-%27switch%27-feature) is considered experimental and is almost certain to undergo changes in the future. (3) You `chomp $base_line` so it has no newline, and then you `print` without a newline. Thus all these "lines" will be one big line. If you `chomp` use `say` (to add a newline), or better don't `chomp` and `print` as you do, since you are just copying whole lines. – zdim Oct 01 '17 at 22:47

1 Answers1

4

You really should check if calls to open succeed.

open(OUT, '>>', $new_file)
   or die("Can't append to \"$new_file\": $!\n");

I bet you'll find that the open is failing, I bet you'll find that it's because the file you specified doesn't exist, and I bet you'll find that $new_file contains a line feed it shouldn't.

The fix is to move the following line to before the open:

chomp $new_file;

By the way, you shouldn't be using global variables. Replace OUT with my $OUT. Same for BASE and APPEND.

ikegami
  • 367,544
  • 15
  • 269
  • 518