Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Trickery with Getopt::Long (flag option, with optional integer arg)

by stevieb (Canon)
on Aug 18, 2017 at 15:03 UTC ( [id://1197613]=perlquestion: print w/replies, xml ) Need Help??

stevieb has asked for the wisdom of the Perl Monks concerning the following question:

I'm in a position with Getopt::Long where I need to allow an option to operate as a flag, but also accept an argument to itself (an integer), and it also must set 0 as the flag value if no integer is passed along with it.

The only way so far I've found to do it involves a bit of workaround, and I'm just wondering if I'm over thinking this. I haven't found another way to do this, so perhaps I'm overlooking something...

use warnings; use strict; use Getopt::Long; my $arg = -1; { local $SIG{__WARN__} = sub { $_[0] =~ /^Option arg/ ? $arg = 0 : warn $_[0]; }; GetOptions( 'arg=i' => \$arg ); } print "$arg\n";

So what that does is sets the argument variable to -1 as a default. If --arg|-a is sent in without an integer value along side it, I catch the warning and if it references the option properly, I set it to 0. If an integer is supplied to the option, things just work as normal.

I'm happy with the code as it works very well, so I'm just looking to find out if there are built-in or other alternatives for this type of situation.

Thanks,

-stevieb

Replies are listed 'Best First'.
Re: Trickery with Getopt::Long (flag option, with optional integer arg)
by toolic (Bishop) on Aug 18, 2017 at 15:12 UTC

      That's great and works exactly as I need, thanks toolic!

      I completely overlooked that in the docs. I was kind of thinking there had to be a way.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1197613]
Approved by choroba
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (2)
As of 2024-04-26 03:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found