Question

I have the following piece of code

my $use = "Use: " . basename($0) . " [options]";
my $version = "Version: 0.1 \n";
my $variableA;
my $variableB;

GetOptions(
'a=s'           => \$variableA,
'help'          => sub { print $use; exit 0 },
'version'       => sub { print $version; exit 0 },
'b'             => sub { \$variableB, &this_subroutine; goto NOWGOHERE; },
 );

die "Incorrect use. \n" unless (defined $variableA || defined $variableB);

sub this_subroutine {

     print "$variableB\n";

}

NOWGOHERE: print "HELLO I'M NOW HERE\n";

What I am trying to do is set $variableB and then do the &this_subroutine and the goto NOWGOHERE but I can only get it to do one or the other, not both, using either 'b=s' => \$variableB, or sub { &this_subroutine; goto NOWGOHERE;0 },

When trying to do both I cannot seem to print the $variableB, is there something obvious I am missing or doing wrong syntactically?

Using 'b=s' => \$variableB, sub { &this_subroutine; goto NOWGOHERE; }, does not seem to work either?

your help is much appreciated, many thanks

Était-ce utile?

La solution

$variableB will never have a value because you never assign to it.

'a=s'           => \$variableA,

gives $variableA a value because, when Getopt::Long is given a scalar ref, it assigns the option's value to that scalar.

On the other hand,

'b'             => sub { \$variableB, &this_subroutine; goto NOWGOHERE; },

gives Getopt::Long a code reference, which it can't assign the option value to.

Based on the docs, it appears that it passes the option name and option value to the coderef as parameters, in which case

'b=s'             => sub { $variableB = $_[1]; this_subroutine(); goto NOWGOHERE; },

should probably do what you want.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top