http://www.perlmonks.org?node_id=11121046


in reply to rename file

rename only file and leave extension alone

The file system doesn't care about extensions. If you wish to retain the extension (or add a different one), then you will have to add that explicitly to the new name.

use CGI; use CGI::Carp qw ( fatalsToBrowser ); use File::Basename; my $upload_dir = "upload/"; my $query = new CGI; my $filename = $query->param("file"); my $upload_filehandle = $query->upload("file"); my $ext = "jpg"; # this can be dynamic based on checking what kind of +file it is my $newname = "edddd.$ext"; my $fileto = rename($filename, $newname); open ( my $UPLOADFILE, ">", $upload_dir/$fileto" ) or die "$!"; binmode $UPLOADFILE; while ( <$upload_filehandle> ) { print $UPLOADFILE; }

Another note is that rename is like mv, which means that you're actually doing a cp and rm (of the original file) if crossing file system boundaries. If this is all happening on the same file system, then it's an atomic rename (fully done or not at all). The "copy" scenario introduces possible file corruption, and what I like to do in that case is an explicit copy, verify the $newname against the $filename, them unlink the $filename.

Update - added my $ to lexical file handle I added to the script.