From: Robert Klemme Date: 2004-11-04T18:33:45+09:00 Subject: Re: From getoptlong to optparse "Massimiliano Mirra - bard" schrieb im Newsbeitrag news:877jp2roei.fsf@prism.localnet... > "Robert Klemme" writes: > > >> while ARGV.first =~ /^-/ > >> opt, arg = opts.get > >> case opt > >> when "--host" > >> config["host"] = arg > >> when "--port" > >> config["port"] = arg.to_i > >> end > >> end > > > > I don't think the code above is proper GetoptLong code. I don't remember > > exactly but the occurrence of ARGV in the loop makes me suspicious. > > > >> I'd like to migrate to optparse, though. But how can I stop argument > >> parsing at a certain point in optparse? > > > > Command line option parsing libs normally do that for you as long as you > > don't have any special requirements. If you need to stop parsing options > > after a special option #terminate might do what you need. > > Not exactly. I need to stop parsing when a special command is seen. > "--host" and "--port" in the above example might appear in a different > order or not appear at all, so they're not reliable. Do you mean the problem is that you need to stop when a command is seen *and* this command can occur anywhere, i.e. also behind an option with an optional argument? > > Reconsidering your situation this is what I'd do: iterative parse all > > remaining options starting with the full set at the beginning. > > Bypassing optparse? No, using it. > > Evaluate the first non option, this is your next command. > > This needs to go hand in hand with option parsing. Consider this: > > $ prog --opt1 arg1 --opt2 stuff --blah > > Is `stuff' a subcommand or opt2's argument? That depends on opt2's > definition (which in GetoptLong means NO_ARGUMENT or > REQUIRED_ARGUMENT). You have the same (or finer) level of control for option arguments in optparse, too. > Then again, if you're thinking that things get > muddy when opt2 has an optional argument, I do agree... Yes, they certainly get muddy at this point. They get as muddy as to be undecidable if you have a command that is also a valid optional argument of an option. You can't decide what it is other than defining a priority for the resolution of this ambiguity. I'm not as much an optparse expert to come up with a quick solution. If there are only special values allowed for a certain option, this might help if optparse has support for it. (I believe I remembered saw something about enumeration arguments but I'm not 100% sure.) > > Eat it and go to the first step only now remembering that options > > are stored for this command. Repeat until there are no more args > > left or the first non option is not a command (i.e. file name, > > ignorable or whatever). > > How is this different from the ARGV loop above? You have two nested loops, one of them is hidden in optparse. Kind regards robert