Perl GetOpt Not Working

I have run into this same problem a few times so I am documenting it here. When using GetOpt::Long and friends I would be mystified when the options were ignored. For example:

#!/usr/bin/perl

use strict;
use warnings;
use Getopt::Long;
my $debug = 0;

my $result = GetOptions( "debug" => $debug );
print "Debug flag is $debug\\n";
wriley ~/bin> ./getopttest.pl
Debug flag is 0
wriley ~/bin> ./getopttest.pl --debug
Debug flag is 0
wriley ~/bin>

The options are completely ignored! A short time of googling later and I remembered the solution.

#!/usr/bin/perl

use strict;
use warnings;
use Getopt::Long;
my $debug = 0;

my $result = GetOptions( "debug" => \\$debug );
print "Debug flag is $debug\\n";
wriley ~/bin> ./getopttest.pl
Debug flag is 0
wriley ~/bin> ./getopttest.pl --debug
Debug flag is 1
wriley ~/bin>

The key is escaping the $ in the GetOptions() statement. If you don’t escapey, it don’t workey!

Comments are closed.