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

后端 未结 2 1024
我寻月下人不归
我寻月下人不归 2020-11-30 12:24

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

2条回答
  •  一向
    一向 (楼主)
    2020-11-30 12:42

    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
    

提交回复
热议问题