in reply to Re^2: Processing arguments with Getopt::Long
in thread Processing arguments with Getopt::Long

I'm not aware of any way to directly declare option dependencies with Getopt::Long.

In theory, you could do ugly things like replacing the option handlers while processing the options, but whether that's "better" than your attempt is questionable... :)

my $result = GetOptions ( "c=s" => \&COMPT1, "t=s" => \&COMPT2, '<>' => sub {print "\nThat is not a valid parameter\n";}, ); sub COMPT1 { my ($optname, $value) = @_; print "Option -$optname is value=$value\n"; # replace error handler for -t with real handler $optname->{linkage}{t} = sub { my ($optname, $value) = @_; print "Option -$optname is value=$value\n"; }; }; sub COMPT2 { # error handler print "Option -t requires option -c\n"; }; __END__ $ ./888928.pl -c foo -t bar Option -c is value=foo Option -t is value=bar $ ./888928.pl -t bar Option -t requires option -c

Note that $optname is an object1, via which you can access the bindings, for example. (I just Data::Dumper'ed the object to see what's in it — maybe you can find a way to do it properly with (documented) methods when you peruse the docs carefully enough...)

Also, the dependency is only "one-way", i.e. it's assumed that -c comes before -t on the command line, and that -c alone makes sense...  If you want "-c without -t" to also be an error, you'll necessarily have to wait until the entire command line has been processed, before checking for failed dependencies.

___

1

Replies are listed 'Best First'.
Re^4: Processing arguments with Getopt::Long
by MKJ747 (Acolyte) on Feb 18, 2011 at 17:25 UTC

    Thanks for taking the time to go through this, Eliya - great example. I will weigh this with the If conditional option and see what looks better. I'm still learning, and every time I figure something out I'm assuming there's a slicker way to do it. Thanks for helping out!

Re^4: Processing arguments with Getopt::Long
by ikegami (Patriarch) on Feb 18, 2011 at 20:36 UTC
    I don't agree with messing with internals of an object (and one that's undocumented at that) just to avoid an extremely simple "if".
      I don't agree with messing with internals of an object...

      Me neither.  Which is why I said "...but whether that's "better" than your (the OP's) attempt is questionable... :)".  I thought that was clear enough.

      Still, learning comes from exploration, so it's not entirely useless to just play with different approaches... even if you're not going to use them in production code in the end.

        I was just voicing my agreement in order to emphasise.