Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can't write to file using print

Tags:

perl

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

like image 278
Haiyuan Zhang Avatar asked Nov 27 '25 19:11

Haiyuan Zhang


2 Answers

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;
like image 71
mob Avatar answered Dec 02 '25 04:12

mob


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.

like image 42
pkaeding Avatar answered Dec 02 '25 05:12

pkaeding



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!