getopt example please

Vladimir Panteleev vladimir at thecybershadow.net
Wed Feb 26 02:37:31 PST 2014


On Wednesday, 26 February 2014 at 09:57:19 UTC, Andrew Edwards 
wrote:
> Request a small example of how to use getopt to accomplish the 
> following:
>
> [1] program subcommand //process subcommand with default 
> arguments if any
> [2] program -h subcommand //output help information about 
> subcommand
> [3] program subcommand --option1 --option2 true option3=log.txt 
> // process subcommand with user specified options

import std.getopt;

void main(string[] args)
{
     bool help;
     getopt(args,
         "h|help", &help,
         config.stopOnFirstNonOption,
     );

     if (args.length == 1)
     {
         // Print general help and list of commands
         return;
     }

     auto subcommand = args[1];
     switch (subcommand)
     {
         case "subcommand":
         {
             if (help)
             {
                 // Print help for subcommand
                 return;
             }

             bool option1;
             string option2, option3;
             getopt(args,
                 "option1", &option1,
                 "option2", &option2,
                 "option3", &option3,
             );

             // Process subcommand with specified options

             break;
         }
         default:
             throw new Exception("Unknown subcommand "~ 
subcommand);
     }
}



More information about the Digitalmars-d-learn mailing list