Tuesday, September 22, 2009

use Getopt::Long;

This mornings very short moment of enlightenment was related to the use of Getopt::Long.

I had been messing with passing command line arguments to my server deployment script and had completely failed to get the --verbose flag to work the way I expected.

So I read the perldoc on it and found that I had been going about this the wrong way altogether.

I had this;

my $VERBOSE = 0;
GetOptions( "config=s" => \$config_file,
"verbose=i" => \$VERBOSE,
"modules" => \$INSTALL_MODULES );

print "DEBUG: message" if $VERBOSE;


Then on the command line I had to specify --verbose 1 or --verbose=1, which really wasn't what I had in mind. So this morning the mist on the man page cleared and it all clicked.

If you use "verbose!" => \$VERBOSE, then you can use --noverbose to unset the flag if you have previously set it in your code above. I'm not sure why I moved to using "verbose=i" => \$VERBOSE, but "verbose" => \$VERBOSE was not working as expected.

Anyhow, I was talking to Andy about putting "!" character after the command line flag name and now --verbose sets the variable $VERBOSE and it behaves as I previously expected.

No comments:

Post a Comment