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

时间:2011-10-10 16:14:49

标签: perl unix

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

  1. 执行像这样的perl脚本有什么好处?
  2. 一旦我们执行perl代码,我们怎样才能使shell脚本像“普通”shell脚本一样工作?
  3. 以下是代码:

    #!/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
    

3 个答案:

答案 0 :(得分:5)

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

$ perl this_script

$ sh this_script

将使用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

答案 1 :(得分:2)

这比已发布的内容简单。

#!$PERLLOCATION/bin/perl

不起作用,因为shebang(#!)行由内核(而不是shell)解释,并且内核不进行变量插值。

代码调用ksh来扩展环境变量并启动指定的Perl安装。

答案 2 :(得分:1)

1。如果您以通常的方式启动Perl脚本:

#!/usr/bin/perl
print "hello world\n";

只有在#!下实际安装了Perl解释器时,/usr/bin行才有效。您展示的perl / ksh双语脚本是一个棘手的方法,即使perl安装在其他地方也能使脚本正常工作。有关更多信息,请参阅例如http://alumnus.caltech.edu/~svhwan/prodScript/invokingPerl.html

2。你做不到。当shell进程遇到exec命令时,它会终止并将控制权移交给perl。 (从技术上讲,它是executes perl in place of the shell, without creating a new process。)之后运行更多shell命令的唯一方法是启动一个新shell。

相关问题