Hi all !
Can anybody tell me why the following code is not copying the file from source to destination?

Thakns in advance........

use File::Copy; 
my $source="C:\\shared\\8.4.1\\DXSI";
my $dest="C:\\r45";
my @files;
my $file;
opendir(DIR, $source) or die "can't opendir $source: $! \n"; 
@files=readdir(DIR); 

close DIR; 
foreach $file(@files)
{
    print "\n $file";
    if($file ne "." || $file ne "..")
    {
if (-f "$source$file")
 {
     chomp($file);
     print "\n copying....";
     copy($source, $dest) or die "Copy Failed: "; 
 }
}
}

Recommended Answers

All 3 Replies

You modify the below lines in your code.

1) if (-f "$source$file")
Add "\\" in between "$source" and "$file" then only it got the valid file path.

2) copy($source, $dest);
Here $source gives the directory name only. File name also must here.


use File::Copy;
my $source="C:\\shared\\8.4.1\\DXSI";
my $dest="C:\\r45";
my @files;
my $file;
opendir(DIR, $source) or die "can't opendir $source: $! \n";
@files=readdir(DIR);

close DIR;
foreach $file(@files)
{
print "\n $file";
if($file ne "." || $file ne "..")
{
if (-f "$source\\$file")
{
chomp($file);
print "\n copying....";
copy("$source\\$file", $dest) or die "Copy Failed: ";
}
}
}

In Windows, the operating system handles file-locking. I haven't looked too closely at your code, but this is a problem that has affected me on several occasions. If the file you're trying to copy is open (or running), Windows may have it locked and prevent Perl from copying it.

Also, I noticed something in your code:

if ( $file ne "." || $file ne ".." )
{
    #...

That conditional expression says "If the file is not '.' (the current directory) OR If the file is not '..' (the parent directory), do the following". Following that logic, when it gets to the current directory entry (.), it'll still execute the block because the second part of the logical OR is true. Likewise, when it gets to the parent directory entry (..), it'll still execute the block because the first part of the logical OR is true. You probably want if ( ($file ne '.') && ($file ne '..') ).

This probably hasn't caused a problem for you because the first statement inside of the block is another conditional block which identifies whether or not the file is a directory. Actually, take out the outer conditional entirely and it'll work just fine ...

# '.' and '..' are directories, so the next if statement
# will exclude them anyway.
# if($file ne "." || $file ne "..")
# {

if ( -f "$source\\$file" )
{
    # The following statement is probably not necessary.
    chomp($file);
    print "\n copying....";
    copy("$source\\$file", $dest) or die "Copy Failed: ";
}

# }

Ghodmode

thank u

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.