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);
5
  • 1
    What happened when you tried this code?
    – mob
    Jun 16, 2011 at 21:21
  • Use of uninitialized value in concatenation (.) or string at ./tst.pl. Also df: -: No such file or directory. Interesting, I still get working output, but with these messgs.
    – jdamae
    Jun 16, 2011 at 21:25
  • 4
    Those mean $opt isn't defined.
    – Eevee
    Jun 16, 2011 at 21:27
  • @Eevee- thanks. that was the problem.
    – jdamae
    Jun 16, 2011 at 21:38

2 Answers 2

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

try to use backslash \$opt, it works.

2
  • 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 you will be able to comment on any post.
    – kylieCatt
    Aug 29, 2014 at 3:36
  • 3
    @IanAuld. Why is this not an answer? Aug 29, 2014 at 4:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.