How do I get Perl's qx
function to execute with my $opt
variable?
Before (works):
my @df_output = qx (df -k /tmp);
I want to use either -k
, -g
, or -H
:
my @df_output = qx (df -$opt /tmp);
There is a strange scalar variable called $_ in Perl, which is the default variable, or in other words the topic. In Perl, several functions and operators use this variable as a default, in case no parameter is explicitly used.
Description. This function is a alternative to using back-quotes to execute system commands. For example, qx(ls -l) will execute the UNIX ls command using the -l command-line option. You can actually use any set of delimiters, not just the parentheses.
$$ The process number of the perl running this script. (Mnemonic: same as shells.) $? The status returned by the last pipe close, backtick (\`\`) command or system operator.
The easiest way is to use the `` feature in Perl. This will execute what is inside and return what was printed to stdout: my $pid = 5892; my $var = `top -H -p $pid -n 1 | grep myprocess | wc -l`; print "not = $var\n"; This should do it.
What you have should work, but: don't ever use qx
. It's ancient and dangerous; whatever you feed to it goes through the shell, so it's very easy to be vulnerable to shell injection or run into surprises if /bin/sh
isn't quite what you expected.
Use the multi-arg form of open()
, which bypasses the shell entirely.
open my $fh, '-|', 'df', "-$opt", '/tmp' or die "Can't open pipe: $!";
my @lines = <$fh>; # or read in a loop, which is more likely what you want
close $fh or die "Can't close pipe: $!";
try to use backslash \$opt
, it works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With