我正在尝试移动文件,但我希望在我这样做之前确保它存在。在Perl中最简单的方法是什么?
我的代码是这样的。我查了open
命令,但我不确定这是最简单的方法。
if #Parser.exe exist in directory of Debug
{
move ("bin/Debug/Parser.exe","Parser.exe");
}
elsif #Parser.exe exist in directory of Release
{
move ("bin/Release/Parser.exe","Parser.exe");
}
else
{
die "Can't find the Parser.exe.";
}
谢谢。
答案 0 :(得分:4)
您可以使用-e
文件测试来检查文件是否存在:
use File::Copy;
if(-e "bin/Debug/parser.exe") {
copy("bin/Debug/parser.exe","Parser.exe") or die "Copy failed: $!";
} elsif(-e "bin/Release/Parser.exe") {
copy("bin/Release/parser.exe","Parser.exe") or die "Copy failed: $!";
} else {
die "Can't find the Parser.exe.";
}
答案 1 :(得分:4)
您需要file test operator来检查文件是否存在。具体来说,您需要-e
运算符来检查文件是否 e xists。
if (-e "bin/Debug/Parser.exe")
{
move ("bin/Debug/Parser.exe","Parser.exe");
}
elsif (-e "bin/Release/Parser.exe")
move ("bin/Release/Parser.exe","Parser.exe");
else
{
die "Can't find the Parser.exe."
}
答案 2 :(得分:4)
我个人不喜欢这些解决方案中文件/路径名的重复 - 为自己说话我怀疑我可能会意外地改变它
if(-e "pathone....")... { copy("pathtwo...","Parser.exe")
我会做像
这样的事情 copy("bin/Debug/parser.exe","Parser.exe") or
copy("bin/Release/parser.exe","Parser.exe") or
die "Can't find the Parser.exe.";
或者如果那有点冒险
copy_parser("bin/Debug") or
copy_parser("bin/Release") or
die "Can't find the Parser.exe.";
sub copy_parser {
my $path = shift ;
my $source = File::Spec-> catfile ( $path, 'Parser.exe' ) ;
if ( -e $source ) {
copy( $source, "Parser.exe") or die "Copy or $source failed: $!";
return 1 ;
}
return 0 ;
}
答案 3 :(得分:2)
不是仅封装代码的复制/移动部分,而是通过封装列表迭代来删除所有重复。
我将子程序放在一个模块中,以便以后可以根据需要重复使用。这也减少了重复的代码。
use SearchMove;
my $found = search_and_move(
src => 'Parser.exe',
dest => 'Parser.exe',
dirs => [
"bin/Debug",
"bin/Release",
],
);
die "Can't find the Parser.exe\n"
unless defined $found;
print "Found Parser.exe in $found";
在SearchMove.pm
包SearchMove;
使用严格; 使用警告;
use Exporter 'import';
our @EXPORT_OK = qw( search_and_move );
our @EXPORT = @EXPORT_OK;
sub search_and_move {
my %arg = @_;
croak "No source file" unless exists $args{src};
croak "No dest file" unless exists $args{dest};
croak "No search paths" unless exists $args{dirs};
my $got_file;
for my $dir ( @{$arg{dirs}} ) {
my $source = "$dir/$arg{src}";
if( -e $source ) {
move( $source, $arg{dest} );
$got_file = $dir;
last;
}
}
return $got_file;
}
1;
现在,您可以在许多不同的项目中使用search_and_move
。