Is it possible to use perl's move
function from File::Copy
module to use a wildcard to move a number of common files with the same file extension?
So far, I can only get move
to work if I explicitly name the files.
For example, I wanted to do something like so:
my $old_loc = "/share/cust/abc/*.dat";
my $arc_dir = "/share/archive_dir/";
Right now, I can do one file like so:
use strict;
use warnings;
use File::Copy;
my $old_loc = "/share/cust/abc/Mail_2011-10-17.dat";
my $arc_dir = "/share/archive_dir/Mail_2011-10-17.dat";
my $new_loc = $arc_dir;
#archive
print "Moving files to archive...\n";
move ($old_loc, $new_loc) || die "cound not move $old_loc to $new_loc: $!\n";
What I want to do at the end of my perl program, move all these files named *.dat
to an archive directory.
You can use Perl's glob
operator to get the list of files you need to open:
use strict;
use warnings;
use File::Copy;
my @old_files = glob "/share/cust/abc/*.dat";
my $arc_dir = "/share/archive_dir/";
foreach my $old_file (@old_files)
{
my ($short_file_name) = $old_file =~ m~/(.*?\.dat)$~;
my $new_file = $arc_dir . $short_file_name;
move($old_file, $new_file) or die "Could not move $old_file to $new_file: $!\n";
}
This has the benefit of not relying on a system call, which is unportable, system-dependent, and possibly dangerous.
EDIT: A better way to do this is just to supply the new directory instead of the full new filename. (Sorry for not thinking of this earlier!)
move($old_file, $arc_dir) or die "Could not move $old_file to $new_file: $!\n";
# Probably a good idea to make sure $arc_dir ends with a '/' character, just in case
From the File::Copy documentation:
If the destination already exists and is a directory, and the source is not a directory, then the source file will be renamed into the directory specified by the destination.
use strict;
use warnings;
use File::Copy;
my $old_loc = "/share/cust/abc/*.dat";
my $arc_dir = "/share/archive_dir/";
for my $file (glob $old_loc) {
move ($file, $arc_dir) or die $!;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With