Perl 脚本:将 mv 作为外部命令运行
我正在尝试将此命令作为我的 perl 脚本的一部分运行:
`mv $n1 ../out`
其中 $n1 是我从先前的子例程中获取的文件名。 我收到如下错误:
mv: missing destination file operand after `test.pl'
Try `mv --help' for more information.
sh: line 1: ../out: is a directory
任何人都可以帮忙吗?如果我单独运行该命令,它运行良好。
I'm trying to run this command as a part of my perl script:
`mv $n1 ../out`
where $n1 is a file name i'm getting from a previous subroutine.
I'm getting a error as below:
mv: missing destination file operand after `test.pl'
Try `mv --help' for more information.
sh: line 1: ../out: is a directory
Can anyone please help. If i run the command individually it runs fine.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一个脚本,它重现了与您看到的错误消息非常相似的内容:
问题是
$n
以换行符结尾(也许您从文件中读取它并且没有chomp
吗?),因此 shell 执行的命令是:如果这确实是问题所在,您可以通过打印
$n1
的值来追踪它:请注意,
语法是旨在捕获 shell 命令的输出。由于您只是重命名文件,因此使用
system
更有意义:或者,正如 Quentin 在评论中建议的那样,使用
File::Copy::move
,或者内置的rename
函数(如果您确定没有跨文件系统边界移动文件)。Here's a script that reproduces something very similar to the error messages you're seeing:
The problem is that
$n
ends with a newline (maybe you read it from a file and didn'tchomp
it?), so the command executed by the shell is:If this is indeed the problem, you could have tracked it down by printing the value of
$n1
:Note that the
syntax is intended to capture the output of a shell command. Since you're just renaming a file, it would make more sense to use
system
:or, as Quentin suggested in a comment, to use
File::Copy::move
, or the built-inrename
function if you're sure you're not moving the file across filesystem boundaries.科纳拉克上面说的。
您可能应该在调用命令之前执行检查,而且如果您不需要使用 system() 而不是使用反引号保存命令的输出,它会使代码更加清晰。
编辑
您可以更改检查以确保您尝试移动的结果存在并且是正常文件:即
What Konerak said above.
You should probably perform a check before calling the command, also if you don't need to save the output of the command use system() rather than back ticks, it makes the code far more legible.
EDIT
You could change the check to ensure that the result you are trying to move exists and is a normal file: ie