6

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);
alex
  • 6,818
  • 9
  • 52
  • 103
jdamae
  • 3,839
  • 16
  • 58
  • 78

2 Answers2

8

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: $!";
Eevee
  • 47,412
  • 11
  • 95
  • 127
  • 4
    `system` returns the exit status, not the process's stdout. But it supports a safe multi-argument form too, yes. – Eevee Jun 16 '11 at 21:21
  • 2
    Noone got around to implementing multi-arg open -| in Windows, though :( – ikegami Jun 17 '11 at 00:33
3

try to use backslash \$opt, it works.

Uyghur Lives Matter
  • 18,820
  • 42
  • 108
  • 144
hack4fun
  • 31
  • 1
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post - you can always comment on your own posts, and once you have sufficient [reputation](http://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](http://stackoverflow.com/help/privileges/comment). – kylieCatt Aug 29 '14 at 03:36
  • 3
    @IanAuld. Why is this not an answer? – Mad Physicist Aug 29 '14 at 04:32