Writing to a file in PERL 5.0 (PERL 6 has few changes) is easy and has many options which are specified while opening the file. Here is a list of different ways to write to a file and the change they bring about in the file.
-------------------------------------------------------------------
#!/usr/local/bin/perl
open(FILE,"+>>outputfile.txt");
print FILE "hello\n";
-------------------------------------------------------------------
Output:(appended at end of file)
-------------------------------------------------------------------
previous
text
hello
-------------------------------------------------------------------
#!/usr/local/bin/perl
open(FILE,"+>outputfile.txt");
print FILE "hello\n";
-------------------------------------------------------------------
Output:(note that previous text is erased and new file is created)
-------------------------------------------------------------------
hello
-------------------------------------------------------------------
#!/usr/local/bin/perl
open(FILE,"+<outputfile.txt");
print FILE "hello\n";
-------------------------------------------------------------------
Output:(note that previous text is replaced starting at the point where the file pointer is located at the time of printing)
-------------------------------------------------------------------
hello
us
text
-------------------------------------------------------------------
But unfortunately if we want to append to the beginning of the file we need to copy the previous text and write it all back in after writing the new text. In such cases using few of the perl modules can solve the problem. In principle its possible that few programs can be writing to the beginning and end of a file at the (nearly)same time.
No comments:
Post a Comment