使用eval在shell脚本中执行perl代码

Sac*_*n S 1 unix perl

我遇到了以下示例.我试着谷歌但找不到太多,所以我在这里发布这个问题.

  1. 执行像这样的perl脚本有什么好处?
  2. 一旦我们执行perl代码,我们如何使shell脚本像"普通"shell脚本一样工作?

这是代码:

#!/bin/ksh
#! -*- perl -*-
eval 'exec $PERLLOCATION/bin/perl -x $0 ${1+"$@"} ;'
if 0;

print "hello world\n";
# how can I make it behave like a "normal" shell script from this point onwards? What needs to be done?
# echo "hello world" ### this results in error
Run Code Online (Sandbox Code Playgroud)

mob*_*mob 7

这个习惯用法在perlrun文档中有描述.该-x开关扫描整个文件,并忽略开头的第一行之前出现任何东西#!,也包含单词perl.这意味着您的系统将使用Perl解释器运行脚本,无论您是perl使用shell命令还是使用shell命令调用脚本(sh/bash/ksh/等等),即

$ perl this_script
Run Code Online (Sandbox Code Playgroud)

$ sh this_script
Run Code Online (Sandbox Code Playgroud)

将运行脚本perl.

为了解决你的第二个问题,这个习惯用法与在同一个文件中组合shell脚本和Perl脚本无关.有几种不同的方法可以解决这个问题,但最可读的方法是编写shell脚本,但使用shell的heredoc表示法来调用perl代码.

#!/bin/bash
# this is a bash script, but there is some Perl in here too

echo this line is printed from the shell
echo now let\'s run some Perl

perl <<EOF
# this is now perl script until we get to the EOF
print "This line is printed from Perl\n";
EOF

echo now this is from the shell script again
Run Code Online (Sandbox Code Playgroud)

  • 值得指出的是,在现代系统中,这种"成语"几乎是不必要的; 它被实现为一种解决方案,用于系统中shebang线不能像你想要的那样工作. (2认同)