The Summary of Option Specifications in the documentation for Getopt::Long indicates that you could almost use:
#!/usr/bin/env perl
use strict;
use warnings;
use Getopt::Long;
my $data = "file.dat";
my $length = 24;
my $verbose = 1;
GetOptions ("length=i" => \$length, # numeric
"file=s" => \$data, # string
"verbose:i" => \$verbose) # optional integer
or die("Error in command line arguments\n");
# Debugging/testing
print "Verbose = $verbose\n";
print "Options:\n";
for my $opt (@ARGV) { print " $opt\n"; }
The : indicates that the value is optional, and the i indicates it takes an integer.
Sample runs (I called the script gol.pl):
$ perl gol.pl
Verbose = 1
Options:
$ perl gol.pl --verbose 0
Verbose = 0
Options:
$ perl gol.pl --verbose=0
Verbose = 0
Options:
$ perl gol.pl --verbose 1
Verbose = 1
Options:
$ perl gol.pl --verbose gooseberry
Verbose = 0
Options:
gooseberry
$ perl gol.pl --verbose
Verbose = 0
Options:
$
There's an 'almost' at the top. As ThisSuitIsBlackNot correctly points out, this sets $verbose to zero when the argument is omitted, which is not what you want.
Your interface is curious. Are you sure you wouldn't be better off with:
--verbose # Enables verbose mode
--noverbose # Disables verbose mode
You can then use "verbose!" to handle that. Also, since verbose mode is enabled by default, there's really no need to support --verbose; there's point in having --verbose 0 to turn it off, or --noverbose, and maybe point in allowing --verbose 9 for extra verbose, etc. You need to think about whether your design is truly appropriate.