开发者

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

开发者 https://www.devze.com 2023-01-11 03:36 出处:网络
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 e

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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消