trevorld / r-optparse

command-line optional argument parser
http://trevorldavis.com/R/optparse/dev/
GNU General Public License v2.0
146 stars 11 forks source link

parse_args returns an error when argument has a leading hyphen #15

Closed cchng closed 9 years ago

cchng commented 9 years ago

Hi,

I'm running into an error when my argument has a leading hyphen.

Code:

library(optparse)

option_list <- list(
    make_option("--range", type="character", help="", dest="range")
    )

optparser <- OptionParser(option_list = option_list, usage="")

opt <- parse_args(optparser)
print(opt$range)

This doesn't seem to be a problem when type is "numeric" and if I only had a single number - but I wanted an input that takes in a list of numbers, including negative numbers, so I used character instead. Any other suggestions welcomed!

Output when argument doesn't have a hyphen:

Rscript optparse_hyphen.R --range 0.1,1
[1] "0.1,1"

Output for argument with a leading hyphen:

Rscript optparse_hyphen.R --range -0.1,1
Error in getopt(spec = spec, opt = args) : 
  flag "range" requires an argument
Calls: parse_args -> getopt
Execution halted

Tried putting quotes around the argument but that doesn't seem to work either:

Rscript optparse_hyphen.R --range "-test"
Error in getopt(spec = spec, opt = args) : 
  flag "range" requires an argument
Calls: parse_args -> getopt
Execution halted

Thanks for looking into this!

Carolyn

trevorld commented 9 years ago

Hi Carolyn,

You need a '=' with your long form option if its argument leads off with a -. In the vignette all example "long form" arguments were of the form --mean=-4.3 which would have worked in your case. Since your option argument does not include any spaces you won't need the quotes.

trevorld@trevorld-Bonobo-Extreme:~$ Rscript test.r --range=-0.1,1
[1] "-0.1,1"

Best,

Trevor

cchng commented 9 years ago

Ahh I overlooked that detail, thanks Trevor!

Best, Carolyn