Reputation: 42842
#!/usr/bin/perl
use strict;
use warnings;
open(my $vmstat, "/usr/bin/vmstat 1 2>&1 |");
open(my $foo, ">", "foo.txt") or die "can't open it for write";
while(<$vmstat>) {
print "get ouput from vmstat and print it to foo.txt ...\n";
print $foo $_;
}
when I run the above code, nothing wrong happend.but after I press ctr-c to quit, nothing in the foo.txt. could any of you tells me why does this happen? thanks in advance.
Upvotes: 3
Views: 2108
Reputation: 118665
Maybe the output is being buffered and you are not being patient enough. Try this extra line of code:
open(my $foo, ">foo.txt") or die "can't open it for write";
select $foo; $| = 1; select STDOUT;
Upvotes: 4
Reputation: 156
You have a typo: "opne" instead of "open".
Also, to read from processes, you must put a pipe at the end:
#!/usr/bin/perl
use strict;
use warnings;
open(my $vmstat, "/usr/bin/vmstat 1 5 2>&1 |") or die "error";
open(my $foo, ">foo.txt") or die "can't open it for write";
while(<$vmstat>) {
print "get ouput from vmstat and print it to foo.txt ...\n";
print $foo $_;
}
Upvotes: 0
Reputation: 37673
There are a couple of issues with this line:
opne(my $foo, ">" "foo.txt") or die "can't open it for write";
First of all, open
is misspelled. Also, you have two strings next to each other, with nothing separating them. Try this:
open(my $foo, ">foo.txt") or die "can't open it for write";
Also, if that doesn't fix your problem, double check that you (or the user this runs as) has write access to the file foo.txt.
Upvotes: 1