getopt usage help to stderr?

Justin Allen Parrott erartqr at gmail.com
Mon May 12 08:22:44 UTC 2025


On Wednesday, 9 April 2025 at 01:23:01 UTC, Salih Dincer wrote:
> On Tuesday, 8 April 2025 at 20:14:56 UTC, Andy Valencia wrote:
>>
>> p.s. Ironically, I could probably have coded a getopt in less 
>> time than I've spent on std.getopt...
>
> :)
>
> Please try the following example with the parameters -h, -e, 
> -l, and -v in that order:
>
> ```d
> import std.array : appender;
> import std.getopt, std.stdio;
>
> void main(string[] args)
> {
>     enum errMsg = "\nPlease try again!";
>     string test;
>     bool verbose;
>
>     try
>     {
>         auto rslt = getopt(
>             args,
>             "exit|e", "Exit process", &test,
>             "verbose|v", "Enable verbose output", &verbose
>         );
>
>         if (rslt.helpWanted)
>         {
>             // Capture help text to a string
>             import std.array : appender;
>             import std.format : formattedWrite;
>
>             auto helpText = appender!string();
>             defaultGetoptFormatter(helpText, args[0], 
> rslt.options);
>
>             // Output to stderr
>             stderr.write(helpText.data);
>             return;
>         }
>     }
>     catch (Exception e)
>     {
>         stderr.writeln(e.msg, errMsg); // ... Please try again!
>         // Also output help on error
>         auto helpText = appender!string();
>         defaultGetoptFormatter(helpText, args[0], 
> getopt(args).options);
>         stderr.write(helpText.data);
>         return;
>     }
>
>     // Your program logic here
>     if (verbose)
>       writeln("Verbose Mode: on");
> }
>
> ```
>
> SDB at 79

You have a redundant call to get opt. I don’t like this much. 
Don’t output help on error


More information about the Digitalmars-d-learn mailing list