Reputation: 31
How can I use a variable in a command used for open along with (-|)
pipe output where the filename is interpreted as a command that pipes output to us.
$cmd = 'ps -elf';
open( my $fh, "-|",$cmd ) || die( "$cmd failed: $! " );
Here I want $cmd = 'ps $myOptions';
where $myOptions
will be set to the required options lets say for example
$myOptions = "-elf"
How can this be done?
Upvotes: 2
Views: 544
Reputation: 16161
Double quoting the pipe works for me:
#!/usr/bin/perl
use strict;
use warnings;
my $cmd = 'ps';
my $opt = "-elf";
open( my $fh, "-|", "$cmd $opt" ) || die( "$cmd failed: $! " );
while( <$fh>) { print "line $.: $_"; }
Also working: "ps $opt"
, join( ' ', $cmd, $opt),
$cmd . ' ' . $optand probably many other ways. You just have to make sure that the 3rd argument to open is a string, with the proper content
ps -elf`. For this you have to make sure you interpolate the variables (ie no single quote), and you don't end up with a list instead of a string (ie concatenate or use variables between double quotes).
Upvotes: 1
Reputation: 44
You can use the string concatenation for this as $cmd = "ps ".$myOptions;
Upvotes: 2
Reputation:
If you want to specify the command as a single string (e.g, if your options may actually consist of several arguments):
my $cmd = "ps $myOptions";
open my $fh, "$cmd |" or die "$cmd failed: $!";
If you want to specify it as two strings (e.g, if $myOptions
should always be treated as a single argument):
open my $fh, "-|", "ps", $myOptions or die "ps $myOptions failed: $!";
Upvotes: 0