Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you create application-level options using Perl's App::Cmd?

Update from FMc

I'm putting a bounty on this question, because I'm puzzling over the same problem. To rephrase the question, how do you implement application-level options (those that apply to an entire program, script.pl), as opposed to those that apply to individual commands (search in this example).

The original question

How can I use App::Cmd to create an interface like this

script.pl --config <file> search --options args

?

I can do:

./script.pl search --options args
./script.pl search args
./script.pl search --options

What I'm trying to achieve is getting an option for the config file like so:

./script.pl --config file.conf search --options args

I've looked at App::Cmd::Tutorial on cpan but so far I haven't had any luck getting it to work.

like image 659
user419056 Avatar asked Aug 13 '10 00:08

user419056


1 Answers

You can specify global options in App::Cmd like below. We need three files:

script.pl:

use Tool;
Tool->run;

Tool.pm:

package Tool;
use strict; use warnings;
use base 'App::Cmd';

sub global_opt_spec {
    ['config=s' => "Specify configuration file"];
}

1;

and Tool/Command/search.pm:

package Tool::Command::search;
use strict; use warnings;
use base 'App::Cmd::Command';

sub opt_spec {
    ["option" => "switch on something"],
}

sub execute {
    my ($self, $opt, $args) = @_;

    warn "Running some action\n";
    warn 'Config file = ' . $self->app->global_options->{config}, "\n";
    warn 'Option      = ' . $opt->{option}, "\n";
}

1;

The example shows how to define global option and access it from within search action.

like image 155
bvr Avatar answered Oct 04 '22 04:10

bvr