How can I process options using Perl in -n or -p mode?

混江龙づ霸主 提交于 2019-11-27 04:40:31

问题


When running perl -n or perl -p, each command line argument is taken as a file to be opened and processed line by line. If you want to pass command line switches to that script, how can I do that?


回答1:


There are three primary ways of passing information to Perl without using STDIN or external storage.

  • Arguments

    When using -n or -p, extract the arguments in the BEGIN block.

    perl -pe'BEGIN { ($x,$y)=splice(@ARGV,0,2) } f($x,$y)' -- "$x" "$y" ...
    
  • Command-line options

    In a full program, you'd use Getopt::Long, but perl -s will do fine here.

    perl -spe'f($x,$y)' -- -x="$x" -y="$y" -- ...
    
  • Environment variables

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



回答2:


Here is a short example program (name it t.pl), how you can do it:

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

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

print $prefix, $_;

Call it like that:

perl -n t.pl file1 file2 file3

or (will add a prefix to every line):

perl -n t.pl -p file1 file2 file3


来源:https://stackoverflow.com/questions/53524699/how-can-i-process-options-using-perl-in-n-or-p-mode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!