1

尽管这个问题与“BioPerl”有关,但我相信这个问题可能比这更笼统。

基本上我已经生成了一个Bio::Tree::TreeI对象,我正在尝试将其转换为字符串变量。

我可以接近将其转换为字符串变量的唯一方法是使用以下命令将该树写入流:

# 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)

->write_tree 的输出是“将树写入流”,但是我如何在字符串变量中捕获它,因为我找不到从Bio::TreeIO中的任何函数返回字符串的另一种方法

4

2 回答 2

3

您可以将标准输出重定向到变量,

my $captured;
{
  local *STDOUT = do { open my $fh, ">", \$captured; $fh };
  $treeOut->write_tree($tree);
}
print $captured;
于 2014-07-08T11:47:11.340 回答
1

通过设置 BioPerl 对象的文件句柄,有一种更简单的方法可以实现相同的目标,而且我认为这不是一个 hack。这是一个例子:

#!/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);

如您所料,运行此脚本会将 newick 字符串打印到您的终端。如果你使用Bio::Phylo(我推荐),有一个to_string方法(IIRC),所以你不必创建一个对象来打印你的树,你可以做say $tree->to_string.

于 2014-07-09T13:53:54.757 回答