如何获得草莓perl中最后执行的命令的值

问题描述 投票:0回答:1

我正在尝试执行一个简单的Strawberry Perl脚本进行文件复制,以从最后执行的命令中获取代码。但是在所有情况下我都得到0 /成功。

我的test.pl脚本中的代码

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"; }

由于我使用的路径D:\\abc\\def\\in\\test\\test1.csv在计算机上不存在,所以我希望失败,但是无论提供什么,我都会成功。

执行和输出后:

D:\ pet \ common \ bin \ backup> perl test.pl成功
perl error-handling copy file-copying strawberry-perl
1个回答
0
投票

如果您查看perldoc File::Copy,您将看到以下内容:

RETURN
    All functions return 1 on success, 0 on failure. $! will be set if an
    error was encountered.

因此,如果有错误,您的代码应公开$!中的内容:

if ( copy($source_file, $target_file)) {
    print "success\n";
} 
else { 
    warn "fail: $!\n";
}

此外,如File :: Copy的文档中所述,copy成功返回1(一个真实值),因此我在成功测试中删除了您的== 0。使用Perl,if(COND){...}语句中的任何true值都可以;您无需显式测试1

关于路径:/字符可用作路径定界符,即使您使用Windows,除非在某些情况下可能会将路径发送到外部程序。此功能使您可以相对方便地编写将路径表示为foo/bar/baz的代码,并且它在Windows下的工作方式与在* nix操作系统下的工作方式类似。使用正斜杠作为分隔符,可以避免转义路径中的每个反斜杠:foo\\bar\\baz

© www.soinside.com 2019 - 2024. All rights reserved.