Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I suppress STDOUT temporarily in a Perl program?

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

like image 847
Karel Bílek Avatar asked Sep 04 '09 00:09

Karel Bílek


2 Answers

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.";
like image 154
Karel Bílek Avatar answered Oct 03 '22 23:10

Karel Bílek


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.

like image 21
Dominic Mitchell Avatar answered Oct 04 '22 01:10

Dominic Mitchell