I am trying to use a function GetOptions
from GetOpt::Long
to call a routine that takes an argument. However, the subroutine is called regardless of whether the parameter is specified on the command line. This unexpected behavior does not occur if the argument is not passed to the routine in the string GetOptions
.
The following is a minimal demonstration of the problem:
If an argument is provided to the subroutine on the line GetOptions
, the subroutine ends with a call, regardless of whether its control parameter is specified on the command line:
$ cat a1.pl
use strict;
use warnings;
use Getopt::Long qw(GetOptions);
my $var="entered";
GetOptions ( "opt" => \&sub1($var) );
sub sub1 { print "sub1 $_[0]\n"; }
$ perl a1.pl --opt
sub1 entered
$ perl a1.pl
sub1 entered
In contrast, if a subroutine is called in GetOptions
without an argument, it behaves accordingly:
$ cat a2.pl
use strict;
use warnings;
use Getopt::Long qw(GetOptions);
GetOptions ( "opt" => \&sub2 );
sub sub2 { print "sub2 entered\n"; }
$ perl a2.pl --opt
sub2 entered
$ perl a2.pl
What am I doing wrong?
PS: , , GetOptions
, GetOptions
, , .