Copy, Rename and Delete Files in Perl

PERLServer Side ProgrammingProgramming Scripts

Here is the Perl example, which opens an existing file file1.txt and read it line by line and generate another copy file file2.txt.

# Open file to read
open(DATA1, "<file1.txt");
# Open new file to write
open(DATA2, ">file2.txt");
# Copy data from one file to another.
while(<DATA1>) {
   print DATA2 $_;
close( DATA1 );
close( DATA2 );

Renaming a file

Here is the Perl example, which shows how we can rename a file file1.txt to file2.txt. Assuming file is available in /usr/test directory.

rename ("/usr/test/file1.txt", "/usr/test/file2.txt" );

This function renames takes two arguments and it just renames the existing file.

Deleting an Existing File

Here is an example, which shows how to delete a file file1.txt using the unlink function.

unlink ("/usr/test/file1.txt");
Updated on 29-Nov-2019 10:22:33