Search code examples
linuxperlcprm

If running cp in a perl script will files that exist be overwritten?


I have a program that will generate pixel intensity values for png images and often those images must be overwritten with new files of the same name because of some failure with the original resulting text file. The question I have is when I copy a new version of that file do the destination directory do I have to remove the destination file with the same name first or will the destination file be over written?

system ("rm -rf /home/alos/Y2H_images/all$intensity");
system ("cp $intensity /home/alos/Y2H_images/all");

Or will executing the copy command in the perl script automatically overwrite the file? Thanks


Solution

  • As was mentioned in the comments, using File::Copy is really the better solution. It will overwrite the destination file (at least on my system).

    use File::Copy;
    copy $intensity, "/home/alos/Y2H_images/all" or die $!;
    

    If you wish to check if the destination file already exists, that can be done with:

    print "File exists: $intensity\n" if -e $intensity;
    

    If you still wish to delete the file before copying it:

    unlink "/home/alos/Y2H_images/all$intensity" or die $!;