Cannot write to file using print
#!/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 bad happens. but after I press ctr-c, we exit, nothing in foo.txt. can any of you tell me why this is happening? thanks in advance.
There are several problems on this line:
opne(my $foo, ">" "foo.txt") or die "can't open it for write";
First of all, it openhas a spelling error. In addition, you have two lines next to each other, nothing separates them. Try the following:
open(my $foo, ">foo.txt") or die "can't open it for write";
, , , ( , ) foo.txt.
You have a typo: "opne" instead of "open".
In addition, to read from processes, you must put an end to 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 $_;
}