Perl "use: command not found" 当 运行 来自 bash 脚本

Perl "use: command not found" when run from bash script

我有一个 Perl 脚本 Info.perl 是这样开始的

#!/usr/bin/perl
#!/usr/bin/bash

use List::Util qw( min max );
use List::MoreUtils qw{ all any };
use Cwd;
use Data::Dumper qw(Dumper);
use Env qw(INFODIR CONFDIR PROCDIR);

当我从终端 运行 它没有问题并且按预期工作时。

但是我有一个 bash 脚本 run.sh 里面只有

./Info.pl

当我 运行 这个脚本时,我得到以下错误

./Info.pl: line 4: syntax error near unexpected token `('
./Info.pl: line 4: `use List::Util qw( min max );'

如果我省略第 4 行,我会收到以下消息:

./Info.pl: line 5: use: command not found
./Info.pl: line 6: use: command not found
./Info.pl: line 7: syntax error near unexpected token `('
./Info.pl: line 7: `use Data::Dumper qw(Dumper);'

我需要用什么特殊的方法 运行 Perl 脚本在 bash 脚本中吗?或者使用 use 命令的任何特殊方法?

删除“#!/usr/bin/bash”是个好主意,因为它是多余的。 在您的脚本中调用“/usr/bin/perl Info.pl”可能会解决问题。

如评论中所述,您的脚本出于某种原因正在通过 shell 执行。您可以研究为什么会这样并修复它。

或者您可以使用以下技巧解决问题:

#!/usr/bin/perl

eval 'exec /usr/bin/perl "[=10=]" "$@"'
    if 0; # not running under some shell

print "Args: @ARGV\n";

如果此脚本是通过 perl 求值的,if 0; 行会阻止 eval 的执行。

然而,shell 没有后缀条件,所以它只执行第一行,运行正确的解释器。

事实上,有很多,不,NUMBER 个 perl 脚本就是这样开始的。 Google 这个 "not running under some shell" 的例子(和一个 explanation 在 SO 上)。