in reply to using a cmd-template

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

Replies are listed 'Best First'.
Re^2: using a cmd-template
by goldenblue (Acolyte) on Dec 11, 2013 at 09:14 UTC
    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.
Re^2: using a cmd-template
by goldenblue (Acolyte) on Dec 11, 2013 at 11:32 UTC

    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.