【问题标题】:how to copy the files form one folder to another with different extension with perl如何使用perl将文件从一个文件夹复制到另一个具有不同扩展名的文件夹
【发布时间】:2014-08-14 02:29:30
【问题描述】:
#!/usr/bin/perl 
use File::Copy; 
print "content-type: text/html \n\n"; #The header 
$filetobecopied = "C:\Users\avinash\Desktop\mktg/"; 
$newfile = "C:\Users\avinash\Desktop\elp/"; 
copy("$.pdf","$.elp") or die "File cannot be copied.";

上面的程序我用来输出但出现错误任何人都可以帮助我输出代码

【问题讨论】:

  • 你能给我们错误信息,让我们看看有什么问题吗?提示:加$!到"File cannot be copied. $1";。这样你就可以看到来自系统的消息了。
  • 抱歉,我没有得到预期的输出,它在 F:\extensionchange.pl 第 6 行的打印中显示如下宽字符错误。无法复制文件。在 F:\extensionchange.pl 第 7 行。
  • 如果添加“$!”在消息的末尾,您会得到无法复制的原因。

标签: perl


【解决方案1】:

如果您使用反斜杠,请对字符串使用单引号,或将反斜杠加倍。在双引号中,很多反斜杠字符都有特殊含义:

my $newfile = "C:\Users\avinash\Desktop\elp/";
print $newfile;

输出:

C:SERSVINASHDESKTOPP/

还有一些隐藏字符:

0000000: 433a 5345 5253 0756 494e 4153 4844 4553  C:SERS.VINASHDES
0000010: 4b54 4f50 1b4c 502f                      KTOP.LP/

【讨论】:

  • 抱歉,我没有得到预期的输出,它在 F:\extensionchange.pl 第 6 行的打印中显示如下宽字符错误。无法复制文件。在 F:\extensionchange.pl 第 7 行。
  • @Eshwar:单引号?
【解决方案2】:

您的脚本存在三个大问题。

  1. 在每个 perl 脚本中始终包含 use strict;use warnings;

    使用这两个Pragmas 是您成为更好的程序员可以做的第一件事。此外,如果他们看到您正在执行基本的尽职调查以自己追踪错误,您将始终从这里的专家那里获得更多帮助。

    在这种情况下,您实际上会在代码中收到两个警告:

    Use of uninitialized value $. in concatenation (.) or string at script.pl line 6.
    Use of uninitialized value $. in concatenation (.) or string at script.pl line 6.
    

    所以你的copy("$.pdf","$.elp") 行是对变量$. 进行插值,因为你还没有从文件中读取,所以该变量是未定义的。

  2. 在双引号字符串中转义反斜杠

    反斜杠在文字字符串定义中具有特殊含义。如果您想在双引号字符串中使用文字反斜杠,则需要对其进行转义。

    在这种情况下,正在翻译以下内容:

    • \Uuc 函数
    • \a是报警代码
    • \D 只是文字 D

    要解决此问题,您需要使用单引号字符串或转义反斜杠

    my $filetobecopied = "C:\\Users\\avinash\\Desktop\\mktg"; # Backslashes escaped
    
    my $filetobecopied = 'C:\Users\avinash\Desktop\mktg';     # Single quotes safer
    

    另外,我不明白为什么你的两个字符串中都有一个尾部正斜杠。

  3. 输出错误信息:$!

    始终在错误消息中包含尽可能多的信息。在这种情况下,File::Copy 执行以下操作:

    所有函数成功返回 1,失败返回 0。如果遇到错误,将设置$!

    因此,您的 or die 语句应包含以下内容:

    copy("fromfile","tofile") or die "Can't copy: $!";
    

    为了获得更好的调试信息,您可以包含您发送到副本的参数:

    copy("fromfile","tofile") or die "Can't copy fromfile -> tofile: $!";
    

无论如何,这三件事将帮助您调试脚本。根据您提供的信息,仍然无法完全解释您的意图,但以下是更好的格式化代码存根:

#!/usr/bin/perl 
use strict;
use warnings;

use File::Copy; 

print "content-type: text/html \n\n"; #The header 

# The following is likely wrong, but the best interpretation of your intent for now:
my $filetobecopied = 'C:\Users\avinash\Desktop\mktg.pdf'; 
my $newfile        = 'C:\Users\avinash\Desktop\elp.elp'; 

copy($filetobecopied, $newfile)
    or die "Can't copy $filetobecopied -> $newfile: $!";

【讨论】:

    猜你喜欢
    • 2018-09-28
    • 1970-01-01
    • 1970-01-01
    • 2021-03-18
    • 1970-01-01
    • 2016-06-06
    • 1970-01-01
    • 1970-01-01
    • 2014-12-02
    相关资源
    最近更新 更多