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


In reply to Re^3: Processing arguments with Getopt::Long by Eliya
in thread Processing arguments with Getopt::Long by MKJ747

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.