How can I suppress STDOUT temporarily in a Perl program?

两盒软妹~` 提交于 2019-12-30 04:56:11

问题


Is there any easy way to tell perl "now ignore everything that is printed"?

I have to call a procedure in an external Perl module, but the procedure prints a lot of unnecessary information (all through standard print).

I know select can be used to redirect it somehow, but I am not too wise from reading perldoc on it.

edit: I found the answer sooner, but I will add an example to make it clearer (but not much I guess)

use TectoMT::Scenario;
use TectoMT::Document;

sub tagDocuments {
    my @documents = @_;

    my $scenario = TectoMT::Scenario->new({'blocks'=> [ qw(
            SCzechW_to_SCzechM::Sentence_segmentation 
            SCzechW_to_SCzechM::Tokenize  
            SCzechW_to_SCzechM::TagHajic
            SCzechM_to_SCzechN::Czech_named_ent_SVM_recognizer) ]});

    $scenario->apply_on_tmt_documents(@documents);
    return @documents;
}

TectoMT::Scenario and TectoMT::Document are those external modules


回答1:


My own answer:

use IO::Null;

print "does print.";

my $null = IO::Null;
my $oldfh = select($null); 

print "does not print.";

select($oldfh);

print "does print.";



回答2:


I realise that this has been answered, but I think it's worth knowing about an alternative method of doing this. Particularly if something is hell-bent on printing to STDOUT

# Store anything written to STDOUT in a string.
my $str;
open my $fh, '>', \$str;
{
  local *STDOUT = $fh;
  code_that_prints_to_stdout();
}

The key bit is local *STDOUT. It replaces the normal STDOUT with a filehandle of your choosing, but only for the scope of the block containing the local.




回答3:


Referring to some answers here and on other threads, I came up with this;

use strict;
use warnings;
use File::Spec;

sub my_functor { system("some_noisy_command.exe", "--option1", "--option2"); }
silently(\&my_functor);

Where "silently()" takes a functor and runs it with stdout redirected:

sub silently($) {
    #Turn off STDOUT
    open my $saveout, ">&STDOUT";
    open STDOUT, '>', File::Spec->devnull();

    #Run passed function
    my $func = $_[0];
    $func->();

    #Restore STDOUT
    open STDOUT, ">&", $saveout;
}



回答4:


open my $saveout, ">&STDOUT";
open STDOUT, '>', "/dev/null";

(do your other stuff here)

open STDOUT, ">&", $saveout;



回答5:


If you want to use only modules in the standard library, File::Spec has the devnull() function. It returns a string representing the null device ("/dev/null" on *nix) that you can presumably open with open().



来源:https://stackoverflow.com/questions/1376607/how-can-i-suppress-stdout-temporarily-in-a-perl-program

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!