Sundeep
Sundeep

Reputation: 3

Content copying across files in perl

I am unable to copy the content of one file to another with below code.

open(DATA1, "+>>text.txt") or die "Couldn't open file text.txt, $!";
open(DATA2, "+>>text11.txt") or die "Error $!";

for ($a = 0; $a < 10; $a++) {
    print DATA1 "Test Line $a\n"
}
while (<DATA1>) {
    print DATA2 "$_";
}

close (DATA1);
close (DATA2);

Can anyone help what went wrong with the code?

Upvotes: 0

Views: 61

Answers (3)

David W.
David W.

Reputation: 107040

First, always use strict and warnings.

If all you want to do is copy one file to another, use File::Copy:

use strict;
use warnings;
use feature qw(say);

use File::Copy;

my $file1 = "...";
my $file2 = "...";

copy $file1, $file2 or die qq(Can't copy '$file1' to '$file2');

Or, you can first open the files. This is convenient if you are already manipulating the files themselves:

use strict;
use warnings;
use autodie;
use feature qw(say);

use File::Copy;

my $file1 = "...";
my $file2 = "...";

open my $fh1, "<", $file1;
open my $fh2, ">", $file2;

copy $fh1, $fh2;

In this second example, I use autodie. This pragma will force your program to abort if a file operation fails. This way, you don't have to keep doing an or die qw(...); after each time you open a file, close it, or write to it.

use File::Copy imports both the copy and move commands to Perl. This is a Standard Module which means that you can use it without worrying whether it will or won't work on a particular system.

Upvotes: 0

amphetamachine
amphetamachine

Reputation: 30595

You have the file opened at the end of the file at first by opening it in "+>>" mode. Printing to it keeps the file position at the end of the file. In order to read from the beginning of the file, you need to seek back to the start:

open(DATA1, "+>>text.txt") or die "Couldn't open file text.txt, $!";
open(DATA2, "+>>text11.txt") or die "Error $!";

for ($a=0; $a<10; $a++){
print DATA1 "Test Line $a\n"}

seek(DATA1, 0,0); # rewind

while(<DATA1>){
print DATA2 "$_";}

close (DATA1);
close (DATA2);

However, if you don't need a whole lot of processing options, you can use File::Copy to simply copy or move files from one location to another. It supports file handles.

Upvotes: 1

mojo
mojo

Reputation: 4132

You should probably seek(DATA1,0,0) to move the file pointer to the beginning before attempting to read from it.

Upvotes: 1

Related Questions