User Tools

Site Tools


perl:command_line_options_and_usage_with_getopt_long
#!/usr/bin/perl
 
use strict;
use Getopt::Long;
 
# declare option-related vars
my $bVerbose;
my $somevalue;
 
# allow "-se" to mean "-s -e", also makes single-letter options case sensitive
Getopt::Long::Configure ("bundling"); 
 
# stop parsing after the first non-option; needed to let you pass options 
# in the host command
Getopt::Long::Configure ("require_order");
 
# parse command line options
exit unless GetOptions(
	"help" => sub { usage(); },
	"verbose|v" => \$bVerbose,
	"number|n=i" => sub { $somevalue = $_[1]; },
	"file|f=s" => sub {
		my $filename = $_[1];
		open FP, "< $filename" or die "$filename: $!\n";
		for (<FP>) { ... }
		close FP;
	},
);
 
if (!@ARGV)  { usage(); }
 
 
 
########################################################################
 
sub usage {
	my $me = $0; $me =~ s/.*[\/\\]//;
 
	print <<EOL;
myapp by Tyler Bletsch
  version $version
 
Description of what it does.
 
Syntax:
  $me [Options] <Arg1> [Arg2] ...
 
Options:
     --help             : Print this message.
  -n,--number <N>       : Something with the number <N>
  -v,--verbose          : Emit extra info to the console during execution
 
EOL
	exit;
}
perl/command_line_options_and_usage_with_getopt_long.txt · Last modified: 2009/08/13 09:57 by tkbletsc

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki