如何在-n或-p模式下使用Perl处理选项?

时间:2018-11-28 17:08:24

标签: perl command-line-interface

运行 <div class="box_general_3"> <div class="indent_title_in"> <i class="pe-7s-clock"></i> <h3>DISPONIBILITÉS</h3> <p>Les horaires de disponibilité du medecin.</p> </div> <div class="wrapper_indent"> <table class = "table"> <thead> <tr> <th> </th> <th> DEBUT </th> <th> FIN </th> </tr> </thead> {% for plan in medecin.planning %} <tbody> <tr> <td> {% if plan.planningLines.isFree is defined %} <strong>{{ plan.planningLines.day }}</strong> </td> <td> {{ plan.starthour }} </td> <td> {{ plan.endhour }} </td> </tr> {% else %} <tr class = "unavailable"> <td> <strong>{{ plan.day }}</strong> </td> <td> {{ plan.starthour }} </td> <td> {{ plan.endhour }} </td> </tr> {% endif %} </tbody> {% endfor %} </table> perl -n时,每个命令行参数都将作为要打开的文件并逐行处理。如果要将命令行开关传递给该脚本,该怎么办?

2 个答案:

答案 0 :(得分:2)

不使用STDIN或外部存储将信息传递给Perl的三种主要方法。

  • 参数

    使用-n-p时,请提取BEGIN块中的参数。

    perl -pe'BEGIN { ($x,$y)=splice(@ARGV,0,2) } f($x,$y)' -- "$x" "$y" ...
    
  • 命令行选项

    在完整程序中,您将使用Getopt::Long,但是perl -s在这里可以正常工作。

    perl -spe'f($x,$y)' -- -x="$x" -y="$y" -- ...
    
  • 环境变量

    X="$x" Y="$y" perl -pe'f($ENV{X},$ENV{Y})' -- ...
    

答案 1 :(得分:0)

这是一个简短的示例程序(将其命名为t.pl),您可以如何做:

#!/bin/perl
use Getopt::Std;

BEGIN {
  my %opts;
  getopts('p', \%opts);
  $prefix = defined($opts{'p'}) ? 'prefix -> ' : '';
}

print $prefix, $_;

这样称呼:

perl -n t.pl file1 file2 file3

或(将为每行添加前缀):

perl -n t.pl -p file1 file2 file3