gokyori
gokyori

Reputation: 367

Perl: Couldn't open a file with file name as input

I am trying to copy lines of a file to another file.I want to give filenames for both input and output file. I tried to do without asking for any input parameters and it worked fine but with filename as input it failed.Here is my code:

use strict;
use warnings;

#names of file to be input and output 
my $inputfile = <STDIN>;
my $outputfile = <STDIN>;

open(INPUT,'<', $inputfile) 
or die "Could not open file '$inputfile' $!";

open(OUTPUT, '>', $outputfile) 
or die "Could not open file '$outputfile' $!";

while (<INPUT>) {
  print OUTPUT;
}

close INPUT;
close OUTPUT;
print "done\n";

Upvotes: 1

Views: 347

Answers (1)

toolic
toolic

Reputation: 62037

chomp your input variables to remove the newlines:

use strict;
use warnings;

#names of file to be input and output 
my $inputfile = <STDIN>;
my $outputfile = <STDIN>;

chomp $inputfile;
chomp $outputfile;

open(INPUT,'<', $inputfile) 
or die "Could not open file '$inputfile' $!";

open(OUTPUT, '>', $outputfile) 
or die "Could not open file '$outputfile' $!";

while (<INPUT>) {
  print OUTPUT;
}

close INPUT;
close OUTPUT;
print "done\n";

Upvotes: 1

Related Questions