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 destinatio开发者_Go百科n 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
It's not Perl which executes the command, it's the shell being invoked by Perl with the given string as its argument.
And yes, it's like any normal copy -- it will clobber any existing file of the same name just as if you'd typed it into the shell yourself, and fail on permission errors etc., just as if you'd typed it into the shell yourself.
Furthermore, wildcard expansions and string escaping are shell-specific and must be considered for portability and security reasons.
You can simply copy the new files over, and the old ones will be replaced.
cp
allows to control overwrite behavior through the i
and n
flags; by default, anyway, files are overwritten.
If you want to be safe in the face of specific error conditions, i.e., the destination file cannot be open, you can specify the -f
flag:
system ("cp -f $intensity /home/alos/Y2H_images/all");
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 $!;
If you're calling it in system
, it acts just like "real life". Yes.
精彩评论