I am trying to use the GetOptions function from GetOpt::Long to call a subroutine that accepts an argument. However, the subroutine gets called regardless of whether the option is specified on the command line. This unexpected behavior does not occur if an argument is not passed to the subroutine in the GetOptions line.
What follows is a minimal demonstration of the problem:
If an argument is provided to the subroutine in the GetOptions line, the subroutine ends up being called regardless of whether its controlling option is supplied on the command line:
$ cat a1.pl
#!/usr/bin/perl
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 the subroutine is called in GetOptions without an argument, it behaves appropriately:
$ cat a2.pl
#!/usr/bin/perl
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: I know that I can simply set a variable that controls whether the subroutine is called after the GetOptions block, but I would like to determine the correct syntax for calling the subroutine within the GetOptions line, as well as understand why the observed behavior is happening.