Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access a Getopt::Long option's value in the option's sub?

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.

like image 540
Cary Millsap Avatar asked Mar 12 '11 07:03

Cary Millsap


1 Answers

From the fine manual:

When GetOptions() encounters the option, it will call the subroutine with two or three arguments. The first argument is the name of the option. (Actually, it is an object that stringifies to the name of the option.) For a scalar or array destination, the second argument is the value to be stored. For a hash destination, the second arguments is the key to the hash, and the third argument the value to be stored.

So, the behavior that you're seeing is documented and you should be safe with it.

like image 63
mu is too short Avatar answered Sep 22 '22 06:09

mu is too short