3

I wanted to use Getopt::Long::GetOptions for getting command line options to the script.

I have a requirement like this:

perl script.pl -c <name1> -c <name2> -m <name3> argument

Here we have option flags -c and -mm which are optional, and argument is mandatory.

Can anyone point out the correct usage for GetOptions?

toolic
  • 57,801
  • 17
  • 75
  • 117
Arpit
  • 4,259
  • 10
  • 38
  • 43

2 Answers2

4

From the Getopt::Long documentation:

GetOptions does not return a false result when an option is not supplied

That's why they're called 'options'.

In other words, if you are expecting a mandatory parameter, you need to explicitly check for it outside of the GetOptions call.


If argument is meant to be part of @ARGV and not the options, use -- to signal the end of options. In the example below, the script would access argument via $ARGV[0]:

perl script.pl -c <name1> -c <name2> -m <name3> -- argument
Community
  • 1
  • 1
Zaid
  • 36,680
  • 16
  • 86
  • 155
  • 1
    Alternatively you can set `pass_through` to let all unknown parameters go to `@ARGV`. `use Getopt::Long qw(:config pass_through)` but beware as this does affect "type checking" on option values. – matthias krull May 23 '13 at 09:24
1

Here's a sample code and result.

https://gist.github.com/kyanny/5634832

If you want to know more about how to handle multiple values option, see documantation: http://perldoc.perl.org/Getopt/Long.html#Options-with-multiple-values

One more thing, Getopt::Long::GetOptions does not provide the way to handle mandatory options. You should check if the mandatory options are in the @ARGV and raise Exceptions, etc. in your hand.

kyanny
  • 1,231
  • 13
  • 20
  • Thanks Kyanny your answer helps. I have another question here I want to use "+" as an option ? Can I do GetOptions( '+=f' => sub {$plus = "true"} ) – Arpit Jun 05 '13 at 10:53