Capturing output - how do I avoid the delay?

C

compuman

Hi

How do avoid the delay when capturing output from a shell command in
Perl?

For example, consider the following example using a find command in a
home directory:

foreach (`find /home/user -type f -print`)
{
print "$_";
}

If I had run the find command on the command line I would see the
output would appear immediately. However putting it into a perl script
like this causes a delay.

I'm guessing that this is because the command is executed first and
then each line is processed by the foreach loop.

However, I want to see the output immediately, just as if I had run
this on the command line.

Any ideas how to achieve this?
 
A

anno4000

compuman said:
Hi

How do avoid the delay when capturing output from a shell command in
Perl?

For example, consider the following example using a find command in a
home directory:

foreach (`find /home/user -type f -print`)
{
print "$_";
}

If I had run the find command on the command line I would see the
output would appear immediately. However putting it into a perl script
like this causes a delay.

I'm guessing that this is because the command is executed first and
then each line is processed by the foreach loop.

How else would it work? The backtick operator returns the output
of the command, so it has to wait for the command to finish before
it can return control to the caller. No other way.
However, I want to see the output immediately, just as if I had run
this on the command line.

Use File::Find (or one of its derivatives) instead of the external
find.

Use the external find, but open a pipe to the process instead of
using backticks (see perldoc -f open, look for pipe).

Anno
 
P

Paul Lalli

Michele said:
If you really have to, then

open my $fh, '-|', 'find /home/user -type f -print' or die "$!\n";
while ($fh) { # ...

I know Michele knows this, but just for the sake of anyone reading this
a year from now...

that should be:

while (<$fh>) { #...

Paul Lalli
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,070
Latest member
BiogenixGummies

Latest Threads

Top