pericmd 025: Dynamic list of subcommands

In one of my applications using Perinci::CmdLine, we have hundreds of subcommands. The subcommands are taken from all the functions in all of the API modules. Instead of updating the CLI application script and adding the subcommand manually to the subcommands attribute hash in the Perinci::CmdLine constructor, I decided that the framework should support dynamic list of subcommands.

So instead of a hash, Perinci::CmdLine also accepts subcommands attribute as a coderef, which is expected to return a hash. An example:

use Perinci::CmdLine::Any;

our %SPEC;

$SPEC{':package'} = {
    v => 1.1,
    summary => 'Demonstrates dynamic subcommands',

$SPEC{noop} = {
    v => 1.1,
    result_naked => 1,
sub noop {}

    url => '/main/',
    subcommands => sub {
        my %subcommands = map { ("subcmd$_" => {url=>"/main/noop"}) } "01".."50";
        return \%subcommands;

The above code will generate 50 subcommands programmatically (although admittedly, in the above contrived example one might as well generate the hash and assign it to the subcommands attribute directly).

Applications for this feature include: a remote client which fetches the list of API functions (or modules + functions) dynamically upon run, so the client does not need to be updated whenever there is a new API function on the server.


Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s