Perl GetOptions, a parameter routine that takes arguments

I am trying to use a function GetOptionsfrom GetOpt::Longto 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
#!/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 a subroutine is called in GetOptionswithout an argument, it behaves accordingly:

$ 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: , , GetOptions, GetOptions, , .

+4
2

, (\&name) ; "", , ( ). . .

,

use warnings;
use strict;
use feature 'say';

use Getopt::Long;

my $opt;
my $var = 'entered';

GetOptions ( 'opt' => sub { $opt = 1; sub1($var) } );

sub sub1 { say "sub1 $_[0]"; }

'opt' => \&cb cb() sub1(...). ( , ) . , , sub1().

, ; \&name. Getopt, .

" ", , , ; , \sub() \( sub() ).

perl -wE'sub tt { say "@_"; return "ret" }; $r = \&tt("hi"); say $$r'

hi
ret

, .

+1

, Perl, , ,

\&sub1($var)

sub1.

GetOptions ( "opt" => \&sub1($var) );

sub($var) GetOptions. , .

:

$ perl -de0

Loading DB routines from perl5db.pl version 1.49_001
Editor support available.

Enter h or 'h h' for help, or 'man perldebug' for more help.

main::(-e:1):   0
  DB<1> sub sub1 { print "sub1\n"; }

  DB<2> sub1()
sub1

  DB<3> &sub1
sub1

  DB<4> \&sub1

  DB<5> x \&sub1
0  CODE(0x804d7fe8)
   -> &main::sub1 in (eval 6)[/usr/lib/perl5/5.22/perl5db.pl:737]:2-2
  DB<6> x \&sub1()
sub1
0  SCALAR(0x804ee7f0)
   -> 1
+1

Source: https://habr.com/ru/post/1689289/


All Articles