I am trying to execute a simple strawberry perl script for file copy to get the code from the last executed command. But I get 0/success in all the case.
Code from my test.pl script
use File::Copy;
use strict;
use warnings;
my $source_file = "D:\\abc\\def\\in\\test\\test1.csv";
my $target_file = "D:\\abc\\def\\in\\test\\test2.csv";
if ( copy( $source_file, $target_file ) == 0 ) {
print "success";
}
else { print "fail"; }
Since the path I used D:\\abc\\def\\in\\test\\test1.csv
does not exist on the machine so I expect to get fail but I get success no matter what I provide.
Following the execution and output:
D:\pet\common\bin\backup>perl test.pl success
If you look at perldoc File::Copy
you will see the following:
RETURN
All functions return 1 on success, 0 on failure. $! will be set if an
error was encountered.
Therefore, your code should be exposing what is in $!
if there is an error:
if ( copy($source_file, $target_file)) {
print "success\n";
}
else {
warn "fail: $!\n";
}
Also, as described in the documentation for File::Copy, copy
returns 1
on success (a true value), so I removed your == 0
in the success test. With Perl, any true value in the if(COND){...}
statement will do; you don't need to explicitly test for 1
.
Regarding paths: The /
character can be used as a path delimiter, even if you're using Windows except in some cases where you might be sending the path to an external program. This capability allows you to relatively portably write code that expresses paths as foo/bar/baz
, and it will work with Windows similarly to how it would work under a *nix operating system. Using the forward slash as a delimiter allows you to avoid escaping every backslash in a path: foo\\bar\\baz
.