goldenblue has asked for the wisdom of the Perl Monks concerning the following question:

so, this is my first question here, I am ready to embarass myself... I would like to write a command template for my procedures, kinda like:
my $cmd_tmpl = { backup => '$bak_cmd $client > $file', list => '$list_cmd -le $client', ... } # all the names of the vars to be substituted my @all_my_vars = qw / bak_cmd client file list_cmd ... / ;
and then call an eval-procedure, later, when the variables are filled, e.g.
sub some_func { my $func = 'backup'; my $client = 'mars'; my $cmd = eval_cmd($func); # here magic happens! seurity_check($cmd); system("$cmd"); }
basically, I want the eval_cmd function to go through my hash, pick the correct key and do a regexp over the variables... something like:
sub eval_cmd { my $key = shift; die "no such command: $key!" unless exists $cmd_template{$key}; my $cmd = $cmd_template{$key}; no strict "vars"; for my $var (@all_my_vars) { $cmd =~ s/\$var/$$var/g if defined $$var; } use strict "vars"; return $cmd; }
does this make any sense, or what's a better way to achieve what I want? Oh, this is how I would use it:
# $client can be given, or not if ($client) { some_func(); } else { foreach $client (@{get_all_running_clients()}) { my $backup-cmd = eval_cmd('backup'); system('$backup-cmd'); } }
Looking for suggestions...

--
I just can't seem to see the forest... all those trees are blocking my sight!

Replies are listed 'Best First'.
Re: using a cmd-template
by kcott (Archbishop) on Dec 09, 2013 at 15:24 UTC

    G'day goldenblue,

    This is something of an XY Problem inasmuch as you've provided a solution idea without specifying the actual problem you are attempting to solve. Consequently, my response is based on guesses regarding the problem and is, therefore, somewhat generic.

    One of the first things that leapt out at me was your use of symbolic references. If you follow that link, you'll find problems with your code: see what it says about package vs. lexical variables and that it's the "refs" stricture (of strict) that will complain about using symbolic references.

    However, I'm not suggesting you fix those coding problems! Use of symbolic references can result in all sorts of problems and I recommend you avoid them unless you have a very good reason not to and know exactly what you are doing and why. For a more detailed discussion, read "Why it's stupid to `use a variable as a variable name' - Parts I, II and III" by Mark Jason Dominus.

    Here's an alternative, general solution that may be better:

    #!/usr/bin/env perl -l use strict; use warnings; my %cmd_gen = ( backup => sub { my ($bak_cmd, $client, $file) = @_; return [ $bak_cmd, $client, '>', $file ]; }, list => sub { my ($list_cmd, $client) = @_; return [ $list_cmd, '-le', $client ]; }, ); my $bak_cmd = 'some_backup_prog'; my $list_cmd = 'some_list_prog'; for my $client (qw{XXX YYY ZZZ}) { my $file = $client . '.bak'; my $backup_cmd_ref = $cmd_gen{backup}->($bak_cmd, $client, $file); #system(@$backup_cmd_ref); # for production print "@$backup_cmd_ref"; # for debugging my $list_cmd_ref = $cmd_gen{list}->($list_cmd, $client); #system(@$list_cmd_ref); # for production print "@$list_cmd_ref"; # for debugging }

    Output:

    some_backup_prog XXX > XXX.bak some_list_prog -le XXX some_backup_prog YYY > YYY.bak some_list_prog -le YYY some_backup_prog ZZZ > ZZZ.bak some_list_prog -le ZZZ

    Some values (e.g. for $bak_cmd and $list_cmd) may be known in advance from configuration, environment variables, defaults, command line options, etc. In this case, your function calls would be simpler, e.g. $cmd_gen{list}->($client).

    -- Ken

      Hi Ken, thx a lot! What you wrote really helps. I'll spend more time on X in the future, instead of Y...

      I had some old code and altered it, trying to stuff some things in there that might not belong there and got frustrated, because it didn't work.

      your suggestion gives me a good idea on what to do and I'll go through the links, hoping to post a better question, next time.

      --
      the singularity will happen.

      Ok, I finally read through the links. Liked this one (Part III) from Mark Jason Dominus most. And got it. I rewrote my code, using objects...
      So, Thanks, again.
      --
      the singularity will happen.
Re: using a cmd-template
by VincentK (Beadle) on Dec 09, 2013 at 17:24 UTC

    Hello goldenblue.

    I am not sure if I fully understand what you are trying to accomplish. I am sure there is a better way to do this, but hopefully what I have listed below will help you. I placed the commands into a Perl module. I inserted tokens in the command hash that will be replaced based on the command input.

    From a script you can include the Commands.pm module. The code below will need to be tweaked in order to parse the correct commands.

    Commands.pm

    #!/usr/bin/perl use strict; use warnings; package Commands; use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $VERSION); use Exporter; our $VERSION=1.0; our @ISA = qw(Exporter); our @EXPORT = qw(%cmd_tmpl eval_cmd); our @EXPORT_OK = qw(); our sub eval_cmd ($); #################################################################### #################################################################### ## Command Hash template our %cmd_tmpl = ( 'backup' => 'token token > token', 'list' => 'token -le token' ); ## Evaluate command , accepts Command , Client, and Arguments our sub eval_cmd ($) { my $array_ref = shift; my $cmd = @{$array_ref}[0]; my $client = @{$array_ref}[1]; my @args; if ( defined @{$array_ref}[2] ) { @args = split(/ /,@{$array_ref}[2]); } die "No such command: $cmd!" unless exists $cmd_tmpl{lc($cmd)}; ## + convert command to lc internally my $cmd_value = $cmd_tmpl{$cmd}; ## update command , replaces first 'token' encountered. $cmd_value =~ s/token/$cmd/; ## update client , replaces first 'token' encountered. $cmd_value =~ s/token/$client/; ## update arguments , replaces first 'token' encountered. for(my $i = 0; $i <=$#args; $i++) { $cmd_value =~ s/token/$args[$i]/; } if ($cmd_value =~ m/token/) { die "Not enough aruments on [@{$array_ref}]"; } return $cmd_value; } #################################################################### #################################################################### 1;

    Command_parser.pl

    #/usr/bin/perl use strict; use warnings; use Commands 1.0; sub Get_Client(); my @clients; die "Error. Usage \'perl Command_parser.pl -Noclient | [-Command Clien +t1 Arguments -Command Client2 Arguments...] \'\n $!" unless $#ARGV > += 0; #################################################################### #################################################################### ## If a client was not provided at the command line, get one if (lc($ARGV[0]) eq "-noclient") { Get_Client(); } else { my @current_command; for(my $i = 0; $i <=$#ARGV; $i++) { if ( $ARGV[$i] =~ m/^\-/ && $i != 0) { # eval current command , then wipe it and keep processing my $command_value = eval_cmd(\@current_command); + print "Command is :$command_value\n"; ##system($command_value); @current_command = (); push @current_command , $ARGV[$i]; $current_command[0] =~ s/\-//g; } elsif ( $i == $#ARGV ) { # eval last command push @current_command , $ARGV[$i]; my $command_value = eval_cmd(\@current_command); print "Command is :$command_value\n"; ##system($command_value); } else { push @current_command , $ARGV[$i]; if ($i == 0) { $current_command[0] =~ s/\-//g; } } } } #################################################################### #################################################################### ## No client was provided at the command line, fill one in sub Get_Client() { my @current_command = ('backup','mars','file1.txt'); my $cmd_value = eval_cmd(\@current_command); # here magic happens! ##security_check($cmd); ##system("$cmd"); }

    Input / Output

    C:\monks\command_template>perl Command_parser.pl -backup client1 myfil +e1.txt -backup client2 myfile2.txt -list client3 Command is :backup client1 > myfile1.txt Command is :backup client2 > myfile2.txt Command is :list -le client3

      Hi Vincent,

      many thanks to you, too for taking so much time without being sure what the question was!

      I like your 'token' aproach and working with listrefs, instead of using named vars.

      I feel like I know now why and where I got stuck, and your post helped me do that! Thank you!

      --
      the singularity will happen.