【问题标题】:perl embed data like in c shellperl 在 c shell 中嵌入数据
【发布时间】:2013-03-02 01:18:13
【问题描述】:

有没有办法将数据嵌入到 perl 脚本中,然后以类似于 c-shell 的方式将其作为临时文件使用/读取。

cat<< eof>tmp.txt
store a multiline text file
eof

run_some_function on [anotherexternalfile] with [tmp.txt]

rm tmp.txt

我想在一个 perl 脚本中嵌入多组命令/数据文件来封装一组命令,以避免需要过多的外部命令文件。

更新

嵌入的文件/数据需要作为输入文件被读取为另一个可执行函数,如下所示。

system("executable.exe [anotherexternalfile] [tmp.txt]");

【问题讨论】:

  • 为什么不使用子程序来存储命令集合
  • 和数据变量
  • 所以你想知道如何写入tmp.txt?
  • 现在你说它听起来很容易。

标签: perl shell command embed


【解决方案1】:

据我了解,perl 具有 DATA 句柄,您可以在其中保存要使用脚本的数据。这样:

#!/usr/bin/env perl

while ( <DATA> ) {
  ## Work with this data as if you were reading it from an external file.
}

__DATA__
some data
more data
and more...

【讨论】:

    【解决方案2】:

    Perl 有“这里的文档”http://perl.about.com/od/perltutorials/qt/perlheredoc.htm。当然 Perl 可以像 shell 一样执行外部命令:http://www.perlhowto.com/executing_external_commands

    【讨论】:

      【解决方案3】:

      它们被称为here-docs,并且受 Perl 支持。

      print <<'__EOI__';
      foo
      bar
      __EOI__
      
      my $x = <<'__EOI__';
      foo
      bar
      __EOI__
      
      for (<<'__EOI__', <<'__EOI__')
      foo
      bar
      __EOI__
      abc
      def
      __EOI__
      {
          print;
      }
      

      【讨论】:

      • 还要注意HERE'和HERE"之间的区别,后者允许变量扩展。
      • 我在我的节点中放置了一个涵盖该内容的链接,但 SO 没有显示它。让我们看看我能不能解决它。
      • 谢谢大家,我不确定这就是我想要的。看起来“here-docs”在您阅读数据时有效。我需要将数据作为另一个函数的一部分和 txt 类型文件读取。
      【解决方案4】:

      根据user1937198的建议:

      my @cmds = (
          "cmd1 arg1 arg2",
          "cmd2 arg1 > somefile",
      );
      for my $cmd (@cmds) {
          system($cmd);
      }
      

      作为对 here-doc 的更完整答案:

      my $cmds = <<CMDS;
      cmd1 arg1 arg2
      cmd2 arg1 > somefile
      CMDS
      
      for my $cmd (split("\n", $cmds)) {
          system("$cmd");
      }
      

      【讨论】:

        猜你喜欢
        • 2018-03-23
        • 2013-04-24
        • 2013-08-06
        • 1970-01-01
        • 2021-04-06
        • 1970-01-01
        • 2010-09-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多