If you are a fan of Getopt::Long and you need to pass negative numbers to your script from the command line, here is a code snippet which can help.

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
    Here's another way to do it that does not require changing the option prefix. From the help for Getopt::long

    "To stop Getopt::Long from processing further arguments, insert a double dash -- on the command line"

    So you can remove that "Getopt::Long::Configure" line from add.pl and call it thusly:
    C:\>add --offset 6 -- -5 result = 1 C:\>
Re: Passing negative numbers on the command line with Getopt::Long
by Anonymous Monk on Nov 20, 2009 at 19:21 UTC

    Interesting, but it appears you are abusing the expectations of an experienced command-line user. As a matter of fact you're not even processing the integer in question with Getopt.

    2 more traditional solutions come to mind:

    Use the options terminator:

    $ add.pl -- -5 $ add.pl -offset -2 -- 12

    or use the "pass_through" option for configuration instead.

    $ add.pl -5 $add.pl -offset -2 -5

    Since you're shifting $value off of the command line anyway this really seems the best way.