【问题标题】:How to introduce a Shell input file as Perl input file如何将 Shell 输入文件作为 Perl 输入文件引入
【发布时间】:2019-02-08 10:25:33
【问题描述】:

我在尝试在我的 Perl 代码中插入 bash 变量时遇到了一些麻烦。 在 Shell 脚本中:-

_input_file     # contain input file name
_output_file    # contain output folder name

如何在 Perl 脚本中引入输入文件和输出文件。因此 Perl 脚本可以读取该输入文件。

【问题讨论】:

  • 您也可以将它们作为参数传递给脚本。或者您是否正在尝试专门访问 shell 环境变量?
  • 我有 3 个脚本,我在一个 shell 脚本中调用所有脚本,所以我在 shell 脚本中指定了输入和输出文件,这样我就可以在所有脚本中调用它们。但我不知道如何将这些变量引入其他脚本。
  • 你也可以使用Getopt::Long perldoc.perl.org/Getopt/Long.html

标签: shell perl


【解决方案1】:

用这个开始你的 Perl 脚本:

#!/usr/bin/perl
use strict;
use warnings;

my $input_file = $ARGV[0]
   or die "usage: $0 <input file> <output file>\n";
my $output_file = $ARGV[1]
   or die "usage: $0 <input file> <output file>\n";

... 然后你可以从 shell 脚本中这样调用它

"${_script_path}/my_perl.pl" "${_input_file}" "${_output_file}"

注意:如果您只有一个输入文件和一个输出文件,那么您应该考虑编写一个过滤器,即从 STDIN 读取并写入 STDOUT。然后就可以像这样集成到管道中了

[command that generates input] | perl my_perl.pl | [command that consumes output]

【讨论】:

  • 我强烈建议引用变量,如perl myscript "$_input_file" "$_output_file"。见mywiki.wooledge.org/BashPitfalls#cp_.24file_.24target。
  • 抱歉,开发者在键盘前睡着了。
  • 我想我只写过滤器或在我的代码中使用Getopt::Long :-)
  • 一种常见的安排是接受输入文件的列表,并简单地在标准输出上产生输出。这样,您的程序就会在 shell 管道中按预期运行。
  • 这些都是有效的 cmets,但我会参考之前的 question。
【解决方案2】:

如果可能,我建议将程序编写为 Unix 过滤器 - 即从 STDIN 读取并写入 STDOUT。这使您的程序尽可能灵活,并且通常更容易编写(因为您避免了所有繁琐的文件打开)。

在 Perl 中,您可以使用 &lt;&gt; 来读取 STDIN 和 print() 来写入 STDOUT。因此,一种常见的方法如下所示:

#!/usr/bin/perl

use strict;
use warnings;

# While there is data available on STDIN
# Read a line and store it in $_
while (<>) {
  # Do something useful with the data in $_
  ...
  # Print $_ to STDOUT
  print;
}

那么你只需要在调用你的程序时确保STDIN和STDOUT连接到正确的文件。如果_input_file 和_output_file 是环境变量并且你的程序被称为my_filter,那么你可以这样称呼它:

my_filter < "$_input_file" > "$_output_file"

【讨论】:

  • "# 虽然 STDIN 上有可用数据" :-)
  • @JRFerguson 哎呀。谢谢,已修复:-/
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-25
  • 1970-01-01
相关资源
最近更新 更多