in reply to Examples for using Getopt::Long
i want to know how using this parser will be more helpful in parsing the command line arguments. and how it will be more difficult with out using the parser?ikegami's example is more verbose and detailed than the typical usage for Getopt::Long, so it might not make the best answer to "how does this module make things easier for me?" :P
As a matter of habit, if you write a lot of command-line scripts that tend to make frequent use of multiple options, you're either going to use Getopt::Long (or Getopt::Std, which would be a bit simpler to use and just as good for your stated needs), or you're going to write some variation on the same "while ( @ARGV and ... )" loop in every script.
For me, it was a matter of realizing how tedious it is to (re)write that while loop every time. If I just want this one script to support options "-u user", "-p passwd", "-h host:port", and some other script to support "-f foo", "-b bar", "-z baz", somehow it seems easier for the scripts to have:
Getopt::Std has an additional method (getopts, as opposed to getopt), which lets you differentiate between options that require args vs. options that set boolean values (e.g. "-v" to turn on "verbose mode").use Getopt::Std; my $Usage = "Usage: $0 -u user -p passwd -h host:port\n" # or "$0 -f foo -b bar -z baz" for some other script # hash to hold option flags, default values: my %opt = ( u => 'me', p => 'secret', h => 'localhost:80' ); my $opts = join '', keys %opt; die $Usage unless ( getopt( $opts, \%opt ) and $opt{u} =~ /\w/ and $opt{p} =~ /\S/ and $opt{h} =~ /\w:\d+$/ ); # adjust or skip the sanity checks as you please
Getopt::Long provides more flexibility for argument checking (being clear about options that take strings vs. numerics vs. no args) and option structure (allowing multivalued options returned as arrays of values -- e.g. "--add this --add that --add the_other"). But Getopt::Std works fine for most cases.
|
|---|