pericmd 019: More on cmdline_aliases

Recall that in a previous post (pericmd 014), the description property in the example mentions about -m and -f options as shortcuts for, respectively, --salutation Mr and --salutation Mrs. How would we implement it?

$SPEC{hello} = {
    v => 1.1,
    summary => 'Say hello',
    args => {
        name => {
            summary => 'Name',
            schema  => 'str*',
            cmdline_aliases => {n=>{}},
            pos => 0,
        },
        salutation => {
            summary => 'Salutation',
            schema  => 'str*',
            cmdline_aliases => {
                s => {},
                f => {
                    summary => 'Set female (shortcut for "-s Mrs")',
                    is_flag => 1,
                    code => sub { $_[0]{salutation} = 'Mrs' },
                },
                m => {
                    summary => 'Set male (shortcut for "-s Mrs")',
                    is_flag => 1,
                    code => sub { $_[0]{salutation} = 'Mr' },
                },
            },
        },
    },
};

The above metadata introduces two new command-line aliases -f and -m. Each alias has their own summary as well as code to set function arguments. The code will receive \%args as its argument and can modify it accordingly. Also note the is_flag alias property. This is to specify that the option does not take value but is only a flag (FYI, setting is_flag is a shortcut for the equivalent longer method: schema => ["bool", is=>1], but who wants to use the latter).

So now you can do:

% ./hello Nobody -f
Hello, Mrs Nobody!

The help message will now also list the command-line aliases separately, as they have their own summaries (as indeed they should, because they are no longer just simple aliases for --salutation):

% ./hello -h
hello - Say hello

Usage:
  hello --help (or -h, -?)
  hello --version (or -v)
  hello [options] [name]
Options:
  --config-path=s     Set path to configuration file
  --config-profile=s  Set configuration profile to use
  --format=s          Choose output format, e.g. json, text
  --help, -h, -?      Display this help message
  --json              Set output format to json
  --naked-res         When outputing as JSON, strip result envelope
  --name=s, -n        Name (=arg[0])
  --no-config         Do not use any configuration file
  --salutation=s, -s  Salutation
  --version, -v       
  -f                  Set female (shortcut for "-s Mrs")
  -m                  Set male (shortcut for "-s Mrs")
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s