Home > Perl > Write contents of one file into another using single program……Its beauty of perl

Write contents of one file into another using single program……Its beauty of perl

Write contents of one file into another using single program……Its beauty of Perl

Yesterday I was learning Perl file I/O and noticed one magical thing about Perl.Yes its magical as I feel this little program has a lot of capability.I am writing below a small program which can take one file content as input and will push the content to another file.Later I will show how to varriablise the program.

Let’s say I have a file called data1.txt located at C:\test\data1.txt.

Program:-

 #!/usr/bin/perl

 #This is a tutorial to show file handling in perl

 

 open(INFILE, "C:\\test\\data1.txt") or die "ERROR:canont open file $!";

 open(OUTFILE, ">C:\\test\\data2.txt") or die "ERROR:cannot create file $!"; 

 

 foreach(<INFILE>){

 print OUTFILE  $_;

 }

 

Now when you will run this program you will find that the contents of data1.txt will be copied to data2.txt.

N:B:-If you want to append the content of a file then you can write the second open() statement as

open(OUTFILE, “>>C:\\test\\data2.txt”);

Now lets say varriablise the program

Modified Program:-

 #!/usr/bin/perl

 #This is a tutorial for file handling in Perl with varriablise file-handles


 

 my $IN = "INFILE";

 my $OUT = "OUTFILE";

 

 $filename1 = "C:\\test\\data1.txt";

 $filename2 = "C:\\test\\data2.txt";

 open($IN, "$filename1" ) or die "ERROR:cannot open file $!";

 open($OUT, ">$filename2") or die "ERROR:cannot create file $!"; 

 

 my @totalcount = <$IN>;

 

 foreach(@totalcount){

 

 print $OUT $_;

 

 }

N:B:-Here you can not declare the variable @totalcount before opening the file handle $IN.

Advertisements
Categories: Perl Tags: , , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: