perl: looping through the output of a 'system' command

Hi there

could anybody point me in the right direction when it comes to looping through the output of a system command in perl (i.e. df -k) doing a test against each line to see if it matches?

for example if i have a df -k output like this and I wanted to grab the lines that matched "sda" or "udev" in the first column

Filesystem           1K-blocks      Used Available Use% Mounted on
/dev/sda3             78412744   4670368  69759224   7% /
udev                   1915252       304   1914948   1% /dev
none                   1915252       540   1914712   1% /dev/shm
none                   1915252       112   1915140   1% /var/run
none                   1915252         0   1915252   0% /var/lock
none                   1915252         0   1915252   0% /lib/init/rw
none                  78412744   4670368  69759224   7% /var/lib/ureadahead/debugfs
/dev/sda2            232571420  75736032 156835388  33% /media/Other HD

any pointers would be great

From perldoc -f open:

So what you need would be something like (untested, needs error checking)

open my $cmd, '-|', 'df -k';
while ($line = <$cmd>) {
}
close $cmd;

thanks Pludi, im not entirely sure i understand exactly what is going on here. but it seems to work as you expected. Specifically, i dont understand the comma separated open/variable declaration bit...... this technique is very new to me

I assumed perl would have a syntactically simple and intuitive way of performing an action such as this. i guess not :slight_smile:

The open could also be written as

open my $file 'df -k|';

, but I find the 3 parameter form (variable, mode, "file") to be more readable. And the variable declaration is advisable here, unless you're reusing an older variable (you are using use strict;, aren't you?)

As for more intuitive, do you mean something like

print foreach `df -k`

If so, it's shorter, but much more unmaintainable.