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

Having a problem with system() recognizing a string literal. OS - Unix (Sun solaris) Code snippet below: CONFIG file has an entry as so:
CMD|/opt/sudo/sudo /usr/bin/su - $ENV{LOGNAME} -c "$someScript"
I read this config file and assign $cmd as so
my $cmd = (split /\|/, $configLine)[1]; system("$cmd");
I was expecting thaT the value for the $ENV{LOGNAME} would be substituted in the system(). But for some reason it is is not capturing the value. Here's whats confusing -I explictly assigned $cmd as
my $cmd = "/opt/sudo/sudo /usr/bin/su - $ENV{LOGNAME} -c \"$someScript +\" "; system("$cmd");
Now it recognizes the value of $ENV{LOGNAME}.. What am i doing wrong in the config file? Note: I have to read commands from the config file only per design. Any help is greately appreciated. Thanks

Replies are listed 'Best First'.
Re: problem with string literal in system()
by cephas (Pilgrim) on Sep 22, 2006 at 02:02 UTC
    You seem to be confused about how interpolation works. In your first example, $cmd is interpolated in the double quotes, and $cmd happens to contain a string that contains some things that look like variables. If you wanted those variables to then be interpolated, you'd need to eval that code somehow. This however would not be considered exactly safe. But to directly answer the question something to the effect of:

    $cmd = eval "\"$cmd\"";

    will give you the string that you want to use in your system command.
      With the given contents of $cmd, that expression won't compile, so $cmd will be undef. If you want templating functionality, use a templating system! Using eval EXPR is such a bad idea.
        Its not trying to execute $cmd. Its wrapping $cmdwith "'s, and then eval'ing. It will return a string with the values interpolated.

        Update: ikegami is correct, the way the command is layed out, it will generate an error. I thought ikegami was trying to point out that the command itself wasn't valid perl, not that it was building an invalid string (that is bad perl). The point of the story is that interpolation doesn't run arbitrarily deep, if you want another layer, you'll have to eval, and get all of the problems that go along with it.
          A reply falls below the community's threshold of quality. You may see it by logging in.