Copy files or directories in Perl programming

by
Share this Article: Facebook0Google+0Twitter0LinkedIn0Reddit0StumbleUpon0

This  script  will  give a  example  how to copy  files  of  directory  of  with   specific  paterns

 

This  script  presented  by  Patrick  Lapre a  member  of  Unixmen  community from Netherlands

if  You have any   comment   or  suggestion  . contact us   from the  unixmen  Forum

 

 

#!/usr/bin/env perl
# Use serveral modules
use warnings;
# Comes in handy for debugging the script
use Data::Dumper;
use File::Copy;

# Define some variables to be used in the script
# A from path and to path are defined
my $from_path = “/Users/carllapre/test/from”;
my $to_path = “/Users/carllapre/test/to”;
# A variable to be used in the foreach loop later on
# An iterator
my $file = “”;
# Define the from location. This is the way the copy
# command works
my $file_new = “”;
my $file_loc = “”;
# A simple array to fill with the info read from
# the directory
my @array = ();

# To open a directory to be read, a stream is created
opendir(TO,$to_path) || die “Can’t open $to_path: $!”;
# To open a directory to be written to, a stream is created
opendir(FROM,$from_path) || die “Can’t open $from_path: $!”;

# A bit tricky. I’m using a grep-function to get the right files
# I’m looking for files, which have the pattern rbs or RBS
@array = grep(/rbs|RBS.*/,readdir(FROM));
# Just a debug tool
print Dumper(@array);

# Whoa the main loop!!!
foreach $file (@array) {
# Create a condition
$file_new = “$to_path/$file”;
# the -e option indicates if a file is existing in the defined directory
if (-e $file_new ) {
print “$file already exists in location $to_pathn”;
}
else {
print “Trying to copy $file to location $to_pathn”;
# this function copies each file to its destination
copy(“$from_path/$file”,”$to_path/$file_loc”) || die “Copy failed: $!”;
}
}

# You must close the streams in the end
closedir(FROM);
closedir(TO);

 

##############################################################################################

#you  have  any  comment  of  suggestion please  let  us  now

###########################################################################################

For questions please refer to our Q/A forum at : http://ask.unixmen.com/

Share this Article: Facebook0Google+0Twitter0LinkedIn0Reddit0StumbleUpon0