You seem to have some . . . let's say misconceptions about what Getopt::Long is for and how to use it. When you pass a sub ref to it you're telling it "Hey, if you see option --test then call this sub". So since you're passing that option, that sub gets called. As is documented, passing a sub is meant to allow more complicated behaviors when receiving an option than (say) "set what this scalar ref points to to the next command line argument" and the sub will receive the option name it's being called for and the value (1, the option was present) as the arguments.
It's not meant to be used to wire up program logic directly.
What you want to be doing would be setting flag variables (start off with my $call_test = undef and then passing ... "test" => \$call_test ...) which then AFTER you've let Getopt::Long parse the options you check and conditionally call whatever subs.
(Also don't add empty paren prototypes willy nilly in your code; they don't do anything useful in this context and would actaully break in normal code calling subs normally if you then try and pass arguments (because you've said they take none).)
Edit: Emphasis added because it's not sinking in.
The cake is a lie.
The cake is a lie.
The cake is a lie.
| [reply] [d/l] [select] |
> i would not want or be expecting "test,1" since i specifically did not pass the parameter test or 1 to the subroutine test
That's how it is supposed to work. You must distinguish between input subs - i.e. get-opt-handlers - and processing subs.
from Getopt::Long#User-defined-subroutines-to-handle-options
When GetOptions() encounters the option, it will call the subroutine with two or three arguments. The first argument is the name of the option.
... For a scalar or array destination, the second argument is the value to be stored.
For a hash destination, the second argument is the key to the hash, and the third argument the value to be stored. It is up to the subroutine to store the value, or do whatever it thinks is appropriate.
Please note that it's possible to call --option arg1 arg2 arg3 and these arguments need to be processed via
'test=s@' => \&test
In your case of a scalar option, the meaning of "test 1" is
- "test" is the name of the option, because you can register the same sub to multiple different options.
- "1" is the default true value for activation of this option
That's consistent with a use case of "test!" => \&test where --no-test will result in a call with test 0 .
use strict;
use warnings;
use Getopt::Long;
GetOptions(
'demo' => \&demo,
'test!' => \&test
)
or die("Error in command line arguments\n");
sub test {
die "expected 2 args" if @_ != 2;
warn join ",",@_;
# demo("hello", "world");
}
__DATA__
OUTPUT: C:/Strawberry/perl/bin\perl.exe -w d:/tmp/pm/getopt_long.pl --no-test
test,0 at d:/tmp/pm/getopt_long.pl line 16, <DATA> line 28.
| [reply] [d/l] [select] |