Getoptlong, getopt, parseopt, which one to use for command l


#1

There seems to be several options out there. Which one should be used
when creating command line tools?


#2

On Sat, 18 Feb 2006, Charlie B. wrote:

There seems to be several options out there. Which one should be used
when creating command line tools?

it keeps things exciting to mix them up in unpredictable ways -
preferably in
obfusicated code.

:wink:

seriously - use getoptlong for simple stuff and optparse if your needs
are
more elaborate.

the big limitation on getoptlong is that it eats ARGV only. most times
this
is fine.

regards.

-a


#3

On 2/17/06, Charlie B. removed_email_address@domain.invalid wrote:

There seems to be several options out there. Which one should be used
when creating command line tools?

I was just looking into that last night, but in my case I wanted to
stick with a standard library so the choices were GetoptLong and
OptionParser. Of those it seems to me that OptionParser is a little
better. Here’s some example code that demonstrates using it. If I’m
not using it in the best way, I’m definitely open to feedback. I’m
also interested in hearing whether there is a better alternative.

To get usage info.: ruby optionparserdemo.rb -h

To take defaults: ruby optionparserdemo.rb

To specify all options: ruby optionparserdemo.rb -n Mark -d 19 -c blue

-f

Example of an invalid option: ruby optionparserdemo.rb -z 42

Example of an invalid value: ruby optionparserdemo.rb -c yellow

Example of another invalid value: ruby optionparserdemo.rb -d foo

require ‘optparse’

Create a Hash containing option default values.

Specified options will replace these.

options = {:name=>‘unknown’, :duration=>5, :color=>‘red’, :final=>false}

Configure an OptionParser.

parser = OptionParser.new
parser.on(’-h’, ‘–help’,
‘displays usage information’) do
puts parser
exit
end
parser.on(’-n=NAME’, ‘–name=NAME’,
‘name of person running experiment’) do |v|
options[:name] = v
end
parser.on(’-d=DURATION’, ‘–duration=DURATION’, Integer,
‘duration in seconds’) do |v|
options[:duration] = v
end
parser.on(’-c=COLOR’, ‘–color=COLOR’, %w(red green blue),
‘color of light’) do |v|
options[:color] = v
end
parser.on(’-f’, ‘–final’, TrueClass,
‘true if final run; false otherwise’) do |v|
options[:final] = true
end

Parse command-line options.

begin
parser.parse($*)
rescue OptionParser::ParseError
puts $!
exit
end

Output the options that will be used.

puts “Options are #{options.inspect}”