How can I allow undefined options when parsing args with Getopt

前端 未结 3 1226
故里飘歌
故里飘歌 2020-12-29 06:26

If I have a command line like:

my_script.pl -foo -WHATEVER

My script knows about --foo, and I want Getopt to set variable

3条回答
  •  自闭症患者
    2020-12-29 06:53

    You need to configure "pass_through" option via Getopt::Long::Configure("pass_through");

    Then it support actual options (e.g. stuff starting with "-" and without the special "--" delimiter to signify the end of "real" options).

    Here's perldoc quote:

    • pass_through (default: disabled)

      Options that are unknown, ambiguous or supplied with an invalid option value are passed through in @ARGV instead of being flagged as errors. This makes it possible to write wrapper scripts that process only part of the user supplied command line arguments, and pass the remaining options to some other program.

    Here's an example

    $ cat my_script.pl
    #!/usr/local/bin/perl5.8 -w
    
    use Getopt::Long;
    Getopt::Long::Configure("pass_through");
    use Data::Dumper;
    my %args;
    GetOptions(\%args, "foo") or die "GetOption returned 0\n";
    print Data::Dumper->Dump([\@ARGV],["ARGV"]);
    
    $ ./my_script.pl -foo -WHATEVER          
    $ARGV = [
              '-WHATEVER'
            ];
    

提交回复
热议问题