djw has asked for the wisdom of the Perl Monks concerning the following question:

I want to run a program and get the output into an array so I use:
@output = `program args`;
But what I need to do is use a variable in part of the args (a directory name):
print "ask for dir: "; chomp(<STDIN> = $dir); @output = `du -h $dir`; # do stuff
Thanks,
djw

Replies are listed 'Best First'.
Re: interpolate using backticks?
by Fastolfe (Vicar) on Sep 21, 2000 at 01:09 UTC
    That should work. You can't assign <STDIN> to $dir though. You probably mean for that to be the other way around.
      Er yup..sorry. :)

      Thanks,
      djw
RE: interpolate using backticks?
by Adam (Vicar) on Sep 21, 2000 at 01:26 UTC
    Course you might want to add some error checking. Maybe a regex to ensure that $dir is for real. You might get some odd results if $dir contained a pipe followed by an undesirable command. (hint... turn on taint checking)
Re: interpolate using backticks?
by djw (Vicar) on Sep 21, 2000 at 02:37 UTC
    Here is the working code:
    #!/usr/bin/perl -w use strict; my (@output, $dir); print "What dir? "; chomp($dir = <STDIN>); @output = `du -h $dir`; foreach (@output) { while (/[0-9][0-9].*?M\s/) { print; last; } }
    Depending on what dir you specify it tells you any sub-directories that have greater than 10Mb worth of files in them. eg checking the amount of dirs in /home/:

    64M     /home/djw
    36M     /home/user
    19M     /home/user2

    I know that there are many other ways to get this, but it went along with what I was trying to learn.

    Thanks,
    djw
RE: interpolate using backticks?
by Anonymous Monk on Sep 21, 2000 at 12:45 UTC
    Argh, forgot my password.... Anyway, the problem with using backticks is that whatever is between the backticks is going to be pass to a shell, so if you interpolate a var with data read from the user, you can do whatever you want. Example: try your code with<
    mail; touch jejejejeje <code> as the input A safer, but more convoluted, way to do this is using open with "-|": <code>open (DA, "-|") || exec "du", "$dir"; @output = <DA>;
    This will fork a process; in the parent, the exec isnt going be executed, as the return of the open will be the PID of the child, and the child will just exec du with the content of $dir as first arg, without passing anything through a shell. In the previous example, it would give you an error: du: mail;touch jejejej: No such file or directory Yes, its more complex, and you may think its unnecessary in your current application, but its better to know a safer way to do it and the risks of the "unsafe" way, to have it in mind if, say, you end up attaching this to a CGI or something. Good luck
      No that's great. I would much rather spend a few more lines typing now and get it right. Much appreciated.

      Thanks,
      djw