- Perl ›
- File operation ›
- here
Move the file Rename the file
To move a file, use the move function of File::Copy module. If it succeeds, it returns true, and if it fails, it returns false. If the move function fails, the details of the error are stored in $!.
use File::Copy 'move'; move ($file_from, $file_to);
You can also move the file to a directory.
use File::Copy 'move'; move $file_from, $dir;
Example
This is an example to move files.
use strict; use warnings; use Fcntl; use File::Copy 'move'; # Move the file (rename the file) my $file = "example_20080522_ $$. txt"; my $dir = "dir_20080522_ $$"; # Prepare files and directories sysopen(my $fh, $file, O_WRONLY | O_CREAT | O_EXCL) or die "Unable to create $file .:$!"; close $fh; print "Preparation:'$file' has been created.\n"; mkdir $dir or die "Unable to create $dir.:$!"; print "Preparation:'$dir' has been created.\n\n"; print "1: Move the file.\n"; my $move_name = "$file.move"; if (move $file, $move_name) { print "$file has been moved to $move_name.\n\n"; } else { warn "Unable to move $file to $move_name. $!"; } print "2; Move the file to the specified directory.\n"; if (move $move_name, $dir) { print "$move_name has been moved to $dir.\n\n"; } else { warn "Unable to move $move_name to $dir .:$!"; }
(Reference) sysopen function, Fcntl