devgp
devgp

Reputation: 1321

Perl: How to pipe output of an open command to a file

I want to run a program and pipe its output to a file. The program could run for several hours, so i want to log all the data that happens while the program is running. How would i do it?

So in perl i have done this so far. As an example, i'm using ifconfig as my program. So in this case i want to output the ifconfig to a file. But the below code is outputting to STDOUT. How do i redirect the output to a text file?

my $program1 = "/sbin/ifconfig";
open my $print_to_file, "|-", $program1, @args;
print $print_to_file;
close($print_to_file);

Upvotes: 1

Views: 2251

Answers (2)

mob
mob

Reputation: 118665

In your example, $print_to_file is an input handle (it is the output stream of the external program, but your Perl script reads from it). So read from it and write its contents to a file through an output filehandle:

open my $read_from_cmd, "|-", $program1, @args;   # an input handle
open my $print_to_file, '>', $the_file;           # an output handle
print $print_to_file <$read_from_cmd>;
close $read_from_cmd;
close $print_to_file;

Upvotes: 1

Ole Tange
Ole Tange

Reputation: 33738

How about:

`$program @args > outfile`

Upvotes: 2

Related Questions