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

1

5

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.

Zoellick answered 12/3, 2011 at 7:12 Comment(0)
I
8

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.

Introduction answered 12/3, 2011 at 7:29 Comment(2)
Errf, I looked right through that paragraph and didn't grok that it contained my answer. Thank you very much for the re-focus.Zoellick
@Cary Millsap: To be fair, the nearby example doesn't illustrate the arguments to the handler, it just shows the simple on/off case and that example is probably what drew your eyes.Introduction

© 2022 - 2024 — McMap. All rights reserved.