new tool: args2env
[hband-tools.git] / user-tools / args2env
blob4910dac10d2e7786693fa008ef554ee313d03d13
1 #!/usr/bin/env perl
3 =pod
5 =head1 NAME
7 args2env - Turns command arguments into environment variables and executes command with the remained arguments
9 =head1 SYNOPSIS
11 args2env [I<OPTIONS>] I<COMMAND> I<ARG_1> I<ARG_2> ... I<ARG_R2> I<ARG_R1>
13 =head1 DESCRIPTION
15 =head1 OPTIONS
17 =over 4
19 =item -a, --arg I<NUM>
21 Move the I<NUM>th argument to the environment by the name B<< ARG_I<NUM> >>
22 (may be overridden by B<--template> option).
23 Counting starts from 1.
24 I<NUM> may be negative number, in which case it's counted from the end backwards.
26 =item -ra, --right-arg I<NUM>
28 Same as B<< --arg -I<NUM> >>.
30 =item -t, --template I<TEMPLATE>
32 How to name environment variables?
33 Must contain a B<%d> macro.
34 Default is B<ARG_%d>.
35 So the value of argument given by B<--arg 1> goes to B<ARG_1> variable.
37 =item -nt, --negative-template I<TEMPLATE>
39 How to name environment variables for arguments specified by negative number?
40 Must contain a B<%d> macro.
41 Default is B<ARG_R%d>, B<R> is for "right", because this arg is counted from the right.
42 So the value of argument given by B<--arg -1> goes to B<ARG_R1> variable.
44 =back
46 =head1 SEE ALSO
48 =cut
51 use Data::Dumper;
52 use Errno qw/:POSIX/;
53 use Getopt::Long qw/:config no_ignore_case no_bundling no_getopt_compat no_auto_abbrev require_order/;
54 use Pod::Usage;
55 no if ($] >= 5.018), 'warnings' => 'experimental::smartmatch';
57 @args_to_move = ();
58 $envname_template = 'ARG_%d';
59 $negative_envname_template = 'ARG_R%d';
61 GetOptions(
62 'a|arg=i@' => \@args_to_move,
63 'ra|right-arg=i@' => sub {
64 my ($getopt, $param) = @_;
65 push @args_to_move, -$param;
67 't|template=s' => \$envname_template,
68 'nt|negative-template=s' => \$negative_envname_template,
69 'help' => sub { pod2usage(-exitval=>0, -verbose=>99); },
70 ) or pod2usage(-exitval=>2, -verbose=>99);
73 for my $arg_num (@args_to_move)
75 my $envname;
76 if($arg_num >= 0) { $envname = sprintf $envname_template, abs $arg_num; }
77 else { $envname = sprintf $negative_envname_template, abs $arg_num; }
78 $ENV{$envname} = $ARGV[$arg_num];
79 delete $ARGV[$arg_num];
81 @ARGV = grep {defined} @ARGV;
83 warn Dumper \@ARGV, {map {$_=>$ENV{$_}} grep {/^ARG/} keys %ENV};
85 exec {$ARGV[0]} @ARGV;