Calling Perl GetOptions twice does not work as expected
I'm struggling to find a Perl GetOptions reference that explains this behavior.
If I call GetOptions twice then the 2nd time I call it, it fails to parse the command-line parameters and they're all returned undefined. Did the 1st call to GetOptions (which, by the way, failed and returned 0) eat the command-line parameters or did the 2nd call simply decide not to bother parsing because it remembered that it had previously failed?
Don't ask why I'm calling GetOptions twice -- it's because the code would be complex to restructure and I'd prefer not to unless necessary. I just want a simple way, in advance of the 'real' call to GetOptions, to test for the presen开发者_开发百科ce of a single command-line parameter. Thanks.
GetOptions
consumes and modifies the @ARGV
array. After calling that function, all that's usually left in that array are the file-name parameters.
If you don't store a copy of the array so you can reset it later, then subsequent GetOptions
calls will have nothing left to parse. You can try calling GetOptionsFromArray
with an arbitrary array instead of using the implicit @ARGV
, too.
GetOptions
removes the options from @ARGV
, leaving you with only the actual arguments, so that the rest of your program doesn't have to be aware of the options when it deals with @ARGV
. I don't see this explicitly mentioned in the documentation, but it's how option parsers generally work.
This does mean that calling it a second time is going to be pretty useless, unless you have some complex schema for options like this: --section1-opt1 --section1-opt2 -- --section2-opt1 --section1-opt2 -- <real arguments>
. The first call would eat up to the first terminating --
, and the second would parse the next section up to the second --
. I can't imagine that being the friendliest of interfaces, though.
As already pointed out, @ARGV
is modified by GetOptions
. Although not a pretty sight, you can declare @ARGV
local:
{
local(@ARGV) = @ARGV;
GetOptions(...);
}
# @ARGV "restored" here
GetOptions(...);
精彩评论