By default Getopt::Long reacts to command line arguments with a dash (-). Thus, if you want to pass -5 on the command line, Getopt::Long will strip off the minus sign and treat that as the option '5'. That will result in an error if you are checking the results of GetOptions.
You can change the default behavior by setting the prefix to something other than '-'. For example, in the code snippet below, prefix is set to the plus sign (+). Refer to Configuring Getopt::Long. Naturally, you should make sure this is well-documented in your usage POD.
use strict; use warnings; use Getopt::Long; Getopt::Long::Configure('prefix=+'); my %opt; GetOptions(\%opt, qw(help offset=i)) or die "error...\n"; $opt{offset} = 3 unless exists $opt{offset}; my $value = shift; print ' result = ', $value + $opt{offset}, "\n";
Here is how it looks from the command line (I called the script add.pl):
$ add.pl 5 result = 8 $ add.pl -5 result = -2 $ add.pl +offset -2 12 result = 10
I recently had the need to do such a thing, but I could not find any examples of using this feature. Perhaps this will be of use to someone in the future. I uploaded my actual script to CPAN: convert_eng
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Passing negative numbers on the command line with Getopt::Long
by catellus (Initiate) on Nov 20, 2009 at 19:27 UTC | |
|
Re: Passing negative numbers on the command line with Getopt::Long
by Anonymous Monk on Nov 20, 2009 at 19:21 UTC |