Search code examples
perlgetopt-long

Can I call Getopts multiple times in perl?


I am a noob to perl, so please try to be patient with this question of mine.

It seems that if I make multiple calls to perl Getopts::Long::GetOpts method, the second call is completely ignored.

  1. Is this normal??(Why)

  2. What are the alternatives to this process??

(Actually Ive written a module, where I make a GetOpts call, an the script using my module tries to do that too, but it seems that script does not get the required options)

Thanks, Neeraj


Solution

  • Getopts::Long alters @ARGV while it works, that's how it can leave non-switch values behind in @ARGV when it is done processing the switches. So, when you make your second call, there's nothing left in @ARGV to parse and nothing useful happens.

    However, there is GetOptionsFromArray:

    By default, GetOptions parses the options that are present in the global array @ARGV. A special entry GetOptionsFromArray can be used to parse options from an arbitrary array.

    So you could use GetOptionsFromArray on a copy of @ARGV (or some other array) if you need to parse the list multiple times.