Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl: Clear contents of file and open file in append mode

Tags:

perl

I need to open a file in append mode in Perl, but I need that before opening file all the data is deleted and fresh data goes in.

I will be entering data line by line, so before entering the first line I need all previous data is deleted.

Please help.

like image 417
kailash19 Avatar asked Sep 05 '11 10:09

kailash19


2 Answers

I think you are confused about what "append" means in perl. What you are describing is opening a file and truncating it, i.e.:

open my $fh, '>', $file;

This will delete the contents of $file and open a new file with the same name.

The reason to use open for appending is when you have a file that you do not wish to overwrite. I.e. the difference between > and >> is simply that the former truncates the existing file and begins writing at the start of the file, and the latter skips to the end of the existing file and starts writing there.

Documentation here

like image 77
TLP Avatar answered Oct 16 '22 10:10

TLP


truncate

like image 29
daxim Avatar answered Oct 16 '22 10:10

daxim