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

2019-02-16 00:25发布

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?

2条回答
时光不老,我们不散
2楼-- · 2019-02-16 01:03

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) } ...$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'...$x...$y...' -- -x="$x" -y="$y" -- ...
    
  • Environment variables

    X="$x" Y="$y" perl -pe'...$ENV{X}...$ENV{Y}...' -- ...
    
查看更多
来,给爷笑一个
3楼-- · 2019-02-16 01:11

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
查看更多
登录 后发表回答