Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute Perl qx function with variable

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);
like image 757
jdamae Avatar asked Jun 16 '11 21:06

jdamae


People also ask

What does $_ mean in Perl?

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.

What does QX do in Perl?

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.

What is $$ in Perl?

$$ 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.

How do you store the output of a command to a variable in Perl?

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.


2 Answers

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: $!";
like image 69
Eevee Avatar answered Sep 22 '22 11:09

Eevee


try to use backslash \$opt, it works.

like image 21
hack4fun Avatar answered Sep 19 '22 11:09

hack4fun