Aion-Run
view release on metacpan or search on metacpan
lib/Aion/Run.pm view on Meta::CPAN
# СоздаÑÑ Ð¾Ð±ÑÐµÐºÑ Ñ Ð¿Ð°ÑамеÑÑами запÑоÑа
sub new_from_args {
my ($pkg, $args) = @_;
my $get_key = sub { my ($feature) = @_; $feature->{opt}{init_arg} // $feature->{name} };
my $FEATURE = $Aion::META{$pkg}{feature};
my $ARG = {};
my $ARGUMENT = {};
exists $_->{arg} and do { $ARG->{$_->{arg}} = $_; $ARGUMENT->{$get_key->($_)} = $_ } for values %$FEATURE;
my %param;
my $set_feature = sub {
my ($key, $val) = @_;
my $feature = $ARGUMENT->{$key} // die "Unknown option --$key";
if($feature->{isa}{name} eq "ArrayRef") {
push @{$param{$key}}, $val;
} else {
die "--$key / $feature->{arg} repeats" if exists $param{$key};
$param{$key} = $val;
}
};
my @args;
for(my $i=0; $i < @$args; $i++) {
local $_ = $args->[$i];
if(/^--([\w-]+)(?:=(.*))?\z/a) {
$set_feature->($1, $2);
}
elsif(/^-(\w+)\z/ai) {
for(split //, $1) {
my $feature = $ARG->{"-$_"} or die "Unknown option -$_";
my $key = $get_key->($feature);
if($feature->{isa}{name} eq "Bool") {
$set_feature->($key, !$feature->{default});
} else {
$set_feature->($key, $args->[++$i]);
}
}
}
else {
push @args, $_;
my $feature;
$set_feature->($get_key->($feature), $_) if $feature = $ARG->{@args};
}
}
if(exists $ARG->{0}) {
my $key = $ARG->{0}{opt}{init_arg} // $ARG->{0}{name};
$param{$key} = \@args;
}
$pkg->new(%param)
}
1;
__END__
=encoding utf-8
=head1 NAME
Aion::Run - role for console commands
=head1 VERSION
0.0.3
=head1 SYNOPSIS
File lib/Scripts/MyScript.pm:
package Scripts::MyScript;
use common::sense;
use List::Util qw/reduce/;
use Aion::Format qw/trappout/;
use Aion;
with qw/Aion::Run/;
# Operands for calculations
has operands => (is => "ro+", isa => ArrayRef[Int], arg => "-a", init_arg => "operand");
# Operator for calculations
has operator => (is => "ro+", isa => Enum[qw!+ - * /!], arg => 1);
#@run math/calc âCalculateâ
sub calculate_sum {
my ($self) = @_;
printf "Result: %g\n", reduce {
given($self->operator) {
$a+$b when /\+/;
$a-$b when /\-/;
$a*$b when /\*/;
$a/$b when /\//;
}
} @{$self->operands};
}
1;
use Aion::Format qw/trappout/;
use lib "lib";
use Scripts::MyScript;
trappout { Scripts::MyScript->new_from_args([qw/-a 1 -a 2 -a 3 +/])->calculate_sum } # => Result: 6\n
trappout { Scripts::MyScript->new_from_args([qw/--operand=4 * --operand=2/])->calculate_sum } # => Result: 8\n
=head1 DESCRIPTION
The C<Aion::Run> role implements the C<arg> aspect for installing features from command line parameters.
=over
( run in 0.488 second using v1.01-cache-2.11-cpan-13bb782fe5a )