Mar 23, 2013

Write to File in Perl


Now, we discuss about writing content to a file

The following code snippet explains
1) Write (">") mode : You write the content to a new file
2) Append (">>") mode : File already exists, you append the content to the existing file
3) You can either define Write or Append mode based on your requirement
4) Define a file read handle (FILE_WRITE), it's can be any user defined name
5) Write the contents to file

file_write.pl

#!/usr/bin/perl

use strict;
use warnings;

my $filename = 'C:\Perl\data_write.txt';

#use the ">"  symbol to write to new file (Write mode)
#use the ">>" to append to the file (Append mode)
open (FILE_WRITE, ">$filename");
#"FILE_WRITE" is File Handle

print FILE_WRITE "\nTesting Writing into Perl file";
print FILE_WRITE "\nWriting more content 111";
print FILE_WRITE "\nWriting more content 222";
close (FILE_WRITE); 

#use the ">"  symbol to write to new file
#use the ">>" to append to the file


Output: 
data_write.txt
Testing Writing into Perl file
Writing more content 111
Writing more content 222



No comments:

Post a Comment