Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: Range in Getopt

by james2vegas (Chaplain)
on Oct 03, 2012 at 06:16 UTC ( #996986=note: print w/ replies, xml ) Need Help??


in reply to Range in Getopt

You can evaluate options with Getopt::Long using a custom subroutine, like this:

use Getopt::Long; my $_debug; GetOptions('d=i' => sub { $_debug = $_[1]; ($_debug > 0 && $_debug <= 4) or die "Invalid Debug Level ($_d +ebug)" } ) and warn $_debug;


GetOptions catches the die and throws it as a warning and returns false. When using the custom subroutine, you need to handle assigning to the variable for your option yourself.


Comment on Re: Range in Getopt
Download Code
Replies are listed 'Best First'.
Re^2: Range in Getopt
by roho (Abbot) on Oct 03, 2012 at 13:26 UTC
    I like your solution, but when no -d parameter is present, the following warning is displayed:

    Warning: something's wrong at C:\tmp\getopt-range.pl line 15.

    This appears to be a warning from Getopt::Long. I tried adding return 1 if !defined @_; at the top of the sub but the warning persists.

    "Its not how hard you work, its how much you get done."

      That is because while the d option's value is required, the d option itself is not, check the definedness of $_debug afterwards:

      use Getopt::Long; my $_debug; GetOptions('d=i' => sub { $_debug = $_[1]; ($_debug > 0 && $_debug <= 4) or die "Invalid Debug Level ($_d +ebug)" } ) or exit 1; die "Debug Level is required" unless defined $_debug; warn "Debug Level is $_debug\n";

      or set a default value before GetOptions:

      use Getopt::Long; my $_debug = 0; GetOptions('d=i' => sub { $_debug = $_[1]; ($_debug > 0 && $_debug <= 4) or die "Invalid Debug Level ($_d +ebug)" } ) or exit 1; warn "Debug Level is $_debug\n";

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://996986]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (14)
As of 2015-07-31 08:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (276 votes), past polls