tags:

views:

60

answers:

3
#!/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.

+1  A: 

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.

pkaeding
@pkeaeding: thanks for indicate me the edit error I've made. but it's definitely not the solution for the problem and I do can write the file ...
Haiyuan Zhang
A: 

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 $_;
}
sespindola
@sespindola: first of all, thanks again tells me the typo I've made, anyway I've fix the two you've mentioned. then, the reason why I downgrade your answer is that instead of while(), while(<$vmstat>) should be used ...
Haiyuan Zhang
don't know why the negative vote, since my code works. :)In any case, by opening processes with a pipe at the beginning youcan write to them. And with a pipe at the end you can read from them.
sespindola
You're right. I used the less then and greater than signs insteadof using their respective html entities.That's why the file descriptor inside wasn't visible.Never mind the vote, glad I could help.
sespindola
@Haiyuan: you can retract your vote now that sespindola has edited it. @sespindola: please format your code correctly in future; HTML entities are not parsed inside code blocks. (Indent by four characters, or highlight the area and click the binary icon.) There is rarely a need to use HTML anywhere in a post; please see the guide: http://stackoverflow.com/editing-help
Ether
+3  A: 

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;
mobrule
better: `use IO::File (); open …; $foo->autoflush(1);`
daxim