kailash19
kailash19

Reputation: 1821

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

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.

Upvotes: 15

Views: 19703

Answers (4)

Krishnachandra Sharma
Krishnachandra Sharma

Reputation: 1342

File handling includes:

  1. Read a file (<)
  2. Write in a file
    1. Append (>>)
    2. Overwrite (>)

For detailed explanation please visit this link.

Upvotes: 2

daxim
daxim

Reputation: 39158

truncate

Upvotes: 7

TLP
TLP

Reputation: 67900

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

Upvotes: 18

clarkb86
clarkb86

Reputation: 693

open(fileHandle, ">", $filePath);

Upvotes: 1

Related Questions