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

I've found some documentation on using the perl -s switch to get variables from the command line, but that's not really what I want. I'd like to take a command line argument that is a string that includes a command and a variable in the Perl script to print.

#!/usr/bin/perl use strict; my $host = 'localhost'; # Use 1 of the following lines: #my $output = eval($ARGV[0]); my $output = $ARGV[0]; print "COMMAND: $output\n"; system($output);

Now call with:

script.pl "echo hello"

Output is:

{C} > script.pl "echo hello" COMMAND: echo hello hello

However, try:

{C} > test "echo $host" COMMAND: echo $host $host

I'd like "$host" that is printed to actually be "localhost" as is set in the script (my $host = 'localhost';) that is output. I had a feeling the "eval" would be needed, but that only works when the argument passed is the variable itself (ie: "$host", not "echo $host" and I need it to be the later since I'd like to pass more complex commands other than just 'echo').

Replies are listed 'Best First'.
Re: Command Line Arg contains Variable and more
by ikegami (Patriarch) on Dec 11, 2009 at 21:52 UTC

    I had a feeling the "eval" would be needed,

    If your argument was Perl code, sure.

    $ perl -e' my $host = "localhost"; eval $ARGV[0]; ' 'system("echo", $host)' localhost

    But your argument is a shell command. That means you'll need to parse the argument as if it was a shell command an interpolate the appropriate variables.

    It would be easier to use a template.

    $ perl -MTemplate -e' Template->new()->process( \$ARGV[0], { host => "localhost" }, \my $cmd ); system($cmd) ' 'echo [% host %]' localhost
Re: Command Line Arg contains Variable and more (pass the buck)
by ikegami (Patriarch) on Dec 11, 2009 at 22:10 UTC

    You could also create environment variables that the shell will be happy to interpolate for you.

    $ perl -e'$ENV{host}="localhost"; system $ARGV[0]' 'echo $host' localhost
    The above is basically the same as
    $ host=localhost sh -c 'echo $host' localhost
Re: Command Line Arg contains Variable and more
by gman (Friar) on Dec 11, 2009 at 21:13 UTC

    Not sure this will work in every arg passed

    Also, doing something like this is probably not the safest

    #!/usr/bin/perl use warnings; use strict; my $string = $ARGV[0]; #print "$string"; my $rc = `$string`; print $rc;

      Changing
      system $cmd;
      to
      print `$cmd`;
      is never a good idea. All it does is introduce memory overhead and lag. It definitely doesn't help the OP interpolate a Perl variable into a shell command.