【问题标题】:Executing perl code inside shell script using eval使用 eval 在 shell 脚本中执行 perl 代码
【发布时间】:2011-10-10 16:14:49
【问题描述】:

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

  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

【问题讨论】:

标签: perl unix


【解决方案1】:

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

$ 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

【讨论】:

  • 需要指出的是,现代系统几乎不需要这个“成语”;它是作为 shebang 线无法按您希望的那样工作的系统的一种解决方法。
  • @tripleee,需要指出的是,OP 实际上并没有使用该成语,并且拥有现代系统在这里无济于事。
【解决方案2】:

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

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

#! 行仅在 Perl 解释器实际安装在 /usr/bin 下时才有效。您展示的 perl/ksh 双语脚本是一个棘手的问题,即使 perl 安装在其他地方,也可以使脚本正常工作。欲了解更多信息,see e.g. this

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

【讨论】:

    【解决方案3】:

    这比已经发布的要简单得多。

    #!$PERLLOCATION/bin/perl
    

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-29
      • 2011-07-12
      • 2015-07-22
      • 1970-01-01
      相关资源
      最近更新 更多