&1 |"); open(my $foo, ">", "...">

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.

+3
source share
3 answers

Perhaps the output is buffered and you are not 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;
+4
source

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.

+1

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 $_;
}
0
source

Source: https://habr.com/ru/post/1756105/


All Articles