How to execute a Perl qx function with a variable

How do I get the Perl 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); 
+4
source share
2 answers

What you need, but : never use qx . It is ancient and dangerous; everything that you feed him passes through the shell, so it is very easy to be vulnerable to shell injections or wonder if /bin/sh not quite what you expected.

Use the multi-arg open() form, which completely bypasses the shell.

 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: $!"; 
+8
source

try using backslash \$opt , it works.

+3
source

All Articles