Kittamaru Kittamaru - 2 months ago 6x
Perl Question

How can I use variables in open(COMMAND, $command) function?

First time asking a question here, so I hope I get the formatting right:

my %config;

#issue the ps grep
my $command = 'ps -ef |grep -w $config{variable1} |grep -wi $config{variable2} |grep -v grep > /wilyagent/BriansPerlTesting/applytest.txt|';
print "Command is ps -ef |grep -w $config{variable1} |grep -wi $config{variable2} |grep -v grep > /wilyagent/BriansPerlTesting/applytest.txt|\n";
print "$command\n";
open( COMMAND, $command )
|| die "Error when executing \"$command\": $!";

Now, my expected output for both would be:

Command is ps -ef |grep -w epaMQMonitor |grep -wi IntroscopeEPAgent |grep -v grep > /wilyagent/BriansPerlTesting/applytest.txt|

Instead, I'm getting this for the second one (and this appears to be what is being run):

ps -ef |grep -w $config{variable1} |grep -wi $config{variable2} |grep -v grep > /wilyagent/BriansPerlTesting/applytest.txt|

Further digging has revealed that Perl is substituting the first level variable ($command) for its contents, but it is not pulling the $config{variable1} and $config{variable2} into it (I think because it considers the $command as a package?)

I found a way to get the output I want:

open my $command, "ps -ef |grep -w $config{variable1} |grep -wi $config{variable2} |grep -v grep > /wilyagent/BriansPerlTesting/applytest.txt|";

However, that doesn't work with an "or die" function on the end.

My question, ultimately; is it possible to get the variable substitution working in the first method, and if so, how?

Background - the reason for this is we have a series of perl scripts currently that are hard-coded. It has been requested that we make these scripts portable to other servers without having to edit the scripts themselves, having them look at a configuration file that lists what they are looking for (in this case, it is a script that looks for processes that should be running on a server).


dgw dgw

In the line

my $command = 'ps -ef |grep -w $config{variable1} |grep -wi $config{variable2} |grep -v grep > /wilyagent/BriansPerlTesting/applytest.txt|';

you set up the variable $command. And since you use single quotes '...' the variables will not be substituted. Use double quotes "..." instead for variable substitution to take place.