My goal is to have a --override=f
option that manipulates the values of two other options. The trick is figuring out how to refer to the option's value (the part matching the f
in the =f
designator) in the sub
that's executed when GetOptions detects the presence of the option on the command line.
Here is how I'm doing it:
$ cat t.pl
#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Long;
our %Opt = (
a => 0,
b => 0,
);
our %Options = (
"a=f" => \$Opt{a},
"b=f" => \$Opt{b},
"override=f" => sub { $Opt{$_} = $_[1] for qw(a b); }, # $_[1] is the "trick"
);
GetOptions(%Options) or die "whatever";
print "\$Opt{$_}='$Opt{$_}'\n" for keys %Opt;
$ t.pl --override=5
$Opt{a}='5'
$Opt{b}='5'
$ t.pl --a=1 --b=2 --override=5 --a=3
$Opt{a}='3'
$Opt{b}='5'
The code appears to handle options and overrides just like I want. I have discovered that within the sub
, $_[0]
contains the name of the option (the full name, even if it's abbreviated on the command line), and $_[1]
contains the value. Magic.
I haven't seen this documented, so I'm concerned about whether I'm unwittingly making any mistakes using this technique.