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


In reply to Passing negative numbers on the command line with Getopt::Long by toolic

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.