Search code examples
stringperlstreambioperl

Capture Output to stream and store as a string variable


Although this question relates to 'BioPerl', the question, I believe, is probably more general than that.

Basically I have produced a Bio::Tree::TreeI object and I am trying to convert that into a string variable.

The only way I can come close to converting that to a string variable is to write that tree to a stream using:

# a $tree = Bio::Tree::TreeI->new() (which I know is an actual tree as it prints to the terminal console)

my $treeOut = Bio::TreeIO->new(-format => 'newick')
$treeOut->write_tree($tree)

The output of ->write_tree is "Writes a tree onto the stream" but how do I capture that in a string variable as I can't find another way of returning a string from any of the functions in Bio::TreeIO


Solution

  • There is an easier way to accomplish the same goal by setting the file handle for BioPerl objects, and I think it is less of a hack. Here is an example:

    #!/usr/bin/env perl
    
    use strict;
    use warnings;
    use Bio::TreeIO;
    
    my $treeio  = Bio::TreeIO->new(-format => 'newick', -fh => \*DATA);
    my $treeout = Bio::TreeIO->new(-format => 'newick', -fh => \*STDOUT);
    
    while (my $tree = $treeio->next_tree) {
        $treeout->write_tree($tree);
    }
    
    __DATA__
    (A:9.70,(B:8.234,(C:7.932,(D:6.321,((E:2.342,F:2.321):4.231,((((G:4.561,H:3.721):3.9623,
    I:3.645):2.341,J:4.893):4.671)):0.234):0.567):0.673):0.456);
    

    Running this script prints the newick string to your terminal, as you would expect. If you use Bio::Phylo (which I recommend), there is a to_string method (IIRC), so you don't have to create an object just to print your trees, you can just do say $tree->to_string.