使用 perl 重命名文本文件时,文本文件末尾出现问号

question marks appers at the end of text file on renaming the text file using perl

我是 Perl 的新手,我试图通过 Perl 脚本下载 link,如下所示:

use strict;
use warnings;
use Cwd qw(abs_path);
use File::Path qw(make_path remove_tree);
use LWP::UserAgent();
use LWP::Simple;
use HTML::LinkExtor;
my $path = abs_path();

print "please provide input link from above for example https://ftp.ncbi.nlm.nih.gov/genomes/ASSEMBLY_REPORTS/prokaryote_type_strain_report.txt\n";
defined(my $link = <>) or die "unable to take arguments from command line $!";
         
my $string = "$link";
$string  =~ s/(.*)\///;
my $text_file = print $';
getstore($link, "$path/links_ncbi/$text_file") or die "unable to get required text file $!\n";

rename("$path/links_ncbi/1", "$path/links_ncbi/$'") or die "unable to rename text file $!\n";

它完成了将所需文本文件下载到所需目录中的工作,但是当我尝试使用重命名函数重命名它时,它也这样做了,但我总是在文本文件名称后面得到一个问号,如下所示:-

prokaryote_type_strain_report.txt?

文件的常量是一样的我检查了但是唯一的是“?”,我无法找出为什么会这样所以我寻求你的指导,请告诉我为什么会这样以及如何排序.我还尝试了以下解决方案:-

vim +'set ff=unix | x' test.pl

dos2unix test.pl

另外,我试过了

sed -i 's/\r$//' test.pl

由于在先前提出的问题中提到了解决方案,但该解决方案是针对 bash 脚本的,但在 Perl 脚本上尝试过,但没有成功。

我也尝试检查它并做了以下操作:-

 print qq{rename("$path/links_ncbi/1", "$path/links_ncbi/$'")} or die "unable to rename text file $!\n";

但一切似乎都很好,请告诉我哪里做错了,为什么这个“?”出现在重命名文件时,非常需要和感谢您的帮助。 谢谢。

是我尝试过的解决方案的 link。

您的 $link 包含换行符,而问号只是此类不可打印字符的占位符。

尝试chomp($link);

您的代码有很多缺陷。我会通过一些点。

my $path = abs_path();

从技术上讲,在像这样的简单程序中,您不需要获取程序文件所在位置的完整路径。您可以只使用相对路径并跳过所有这些逻辑。

defined(my $link = <>) or die "unable to take arguments from command line $!";

这是不正确的。因为 <> 从输入文件或标准输入中读取,所以它可能总是被定义,至少包含一个换行符或一个空字符串。你可以这样做:

chomp(my $link = <>);
die "Argument required" unless $link;

这个

my $string = "$link";

将输入复制到新变量毫无意义。使用双引号将变量插入字符串也是没有意义的。

$string  =~ s/(.*)\///;
my $text_file = print $';

您 trim 输入字符串,带有相当不安全的正则表达式,它将“在斜线 / 之前使用任何字符 0 次或多次,然后不替换任何内容。存储匹配的</code> 中的字符(因为括号)".</p> <p>然后你打印 <code>$' post 匹配变量,returns 1 到 $text_file,因为打印总是 returns 1。你可能只是 return $',其中可能包含您的文件名。或者只使用 $string,它应该包含相同的内容,因为您删除了最后一个斜线之前的所有内容。

getstore($link, "$path/links_ncbi/$text_file") or die "unable to get required text file $!\n";
rename("$path/links_ncbi/1", "$path/links_ncbi/$'") or die "unable to rename text file $!\n";

所以现在您 getstore 将文件命名为 1,然后将文件从 1 重命名为 $'。呸!这是个复杂的东西。

跳过所有这些,使用类似

的东西
chomp(my $link = <>);
die "Argument required" unless $link;
my $filename = $link =~ s/.*\///r;     # remove path return file name
getstore($link, $filename);