无法使用打印写入文件 [英] can't write to file using print

查看:72
本文介绍了无法使用打印写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#!/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 $_;
}

当我运行上面的代码时,没有发生任何错误.但是在我按 ctr-c 退出后,foo.txt 中没有任何内容.你们中有人能告诉我为什么会这样吗?提前致谢.

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.

推荐答案

可能是输出被缓冲了而你不够耐心.试试这行额外的代码:

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;

这篇关于无法使用打印写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆