【问题标题】:Embedded Perl in Shell Script - Returning value to ParentShell 脚本中的嵌入式 Perl - 将值返回给父级
【发布时间】:2013-06-11 13:07:56
【问题描述】:

出于某种原因,我需要在 Bash 中运行 perl 脚本。但是 perl 中有一个计数器,我想在 shell 脚本(父级)中使用它。但由于某种原因,我无法获取它。

有人可以帮我解决这个问题吗? (我正在做的唯一选择是在文件中编写 perl 返回代码,然后在 shell 脚本(父级)中读取文件以获取值)。

#!/bin/sh
cnt=1
echo "In Bash (cnt: $cnt)"
perl - $cnt <<'EOF'
    #!/usr/bin/perl -w
    my $cnt=shift;
    while ($cnt<100) {
        $cnt++;
    }
    print "In Perl (cnt: $cnt)\n";
    exit $cnt;
EOF
echo "In Bash (cnt: $cnt)"

输出:

$ ./testPerl
在 Bash (cnt: 1)
在 Perl (cnt: 100)
在 Bash 中 (cnt: 1)

【问题讨论】:

  • 您不能在完全不同的语言之间共享变量!要么发出一段 shell 脚本,在 eval'd 时将变量设置为正确的值,要么在 Bash 中解析 Perl 输出!另请参阅this recent question
  • 但它与使用返回码退出 perl 不一样。如果我们可以在 perl 中传递 shell 变量,我们将得到一个返回码。
  • 退出代码用于指示进程是成功还是退出并出现错误。您的 bash 脚本甚至从不查看 perl 脚本的退出代码。与任何其他程序一样,使用 STDOUT 返回数据。您会发现像反引号或 $(command) 这样的 bash 结构很有用。

标签: perl bash shell exit


【解决方案1】:
#!/bin/sh
cnt=1
echo "In Bash (cnt: $cnt)"
cnt=`perl -e '
    my $cnt=shift;
    while ($cnt<100) {
        $cnt++;
    }
    print $cnt;
    exit' $cnt`
echo "In Bash (cnt: $cnt)"

【讨论】:

    【解决方案2】:

    @askovpen 在我之前回答了这个问题。我想证明如果你愿意,你仍然可以使用heredoc:

    #!/bin/sh
    cnt=1
    echo "before (cnt: $cnt)"
    cnt=$(
    perl -l - $cnt <<'EOF'
        $x = shift;
        $x++ while $x < 100;
        print $x;
    EOF
    )
    echo "after (cnt: $cnt)"
    

    我更改了 perl 的变量名,以明确该变量根本不共享

    【讨论】:

      【解决方案3】:
      #!/bin/sh
      cnt=1
      echo "In Bash (cnt: $cnt)"
      perl - $cnt <<'EOF'
          #!/usr/bin/perl -w
          my $cnt=shift;
          while ($cnt<100) {
              $cnt++;
          }
          print "In Perl (cnt: $cnt)\n";
          exit $cnt;
      EOF
      cnt=$?;
      echo "In Bash (cnt: $cnt)"
      

      【讨论】:

      • 虽然这可行,但这是一个非常糟糕的主意。退出代码是 0 到 255(一个字节)范围内的整数。很容易出现溢出错误。
      • 我认为你是对的阿蒙。这就是正在发生的事情。正在返回 cnt,但如果 cnt 的值 > 255,则将其包装,并从 0 重新启动。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-17
      • 1970-01-01
      • 1970-01-01
      • 2012-01-02
      • 1970-01-01
      相关资源
      最近更新 更多